From b405fd6629f7d8c4f96b27c6ad9010f2a4e2cf81 Mon Sep 17 00:00:00 2001 From: Manali Shah Date: Fri, 25 Mar 2022 17:45:38 -0300 Subject: [PATCH 1/4] Refactoring code --- .../java/org/asdfjkl/jerryfx/gui/App.java | 10 +- .../org/asdfjkl/jerryfx/gui/Chessboard.java | 115 ++++------- .../asdfjkl/jerryfx/gui/EngineController.java | 43 +++- .../asdfjkl/jerryfx/gui/EnterPosBoard.java | 25 +-- .../jerryfx/gui/GameMenuController.java | 44 ++-- .../org/asdfjkl/jerryfx/gui/GameModel.java | 101 +-------- .../jerryfx/gui/ModeMenuController.java | 192 ++++++------------ .../org/asdfjkl/jerryfx/gui/PgnDatabase.java | 113 +++-------- .../jerryfx/gui/PieceImageProvider.java | 106 +++++----- ...Util.java => RandomFileNameGenerator.java} | 2 +- .../jerryfx/gui/ShowAppearanceBoard.java | 39 +--- 11 files changed, 257 insertions(+), 533 deletions(-) rename src/main/java/org/asdfjkl/jerryfx/gui/{Util.java => RandomFileNameGenerator.java} (92%) diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/App.java b/src/main/java/org/asdfjkl/jerryfx/gui/App.java index 76cc4db2..2bbfc9ba 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/App.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/App.java @@ -375,7 +375,7 @@ btnFullAnalysis, new Separator(), EditMenuController editMenuController = new EditMenuController(gameModel); gameModel.addListener(modeMenuController); - modeMenuController.activateEnterMovesMode(); + engineController.activateEnterMovesMode(gameModel); itmSaveCurrentGameAs.setOnAction(e -> { gameMenuController.handleSaveCurrentGame(); @@ -442,7 +442,7 @@ btnFullAnalysis, new Separator(), itmEnterMoves.setOnAction(actionEvent -> { tglEngineOnOff.setSelected(false); tglEngineOnOff.setText("Off"); - modeMenuController.activateEnterMovesMode(); + engineController.activateEnterMovesMode(gameModel); }); itmFullGameAnalysis.setOnAction(actionEvent -> { @@ -457,7 +457,7 @@ btnFullAnalysis, new Separator(), } else { itmEnterMoves.setSelected(true); tglEngineOnOff.setText("Off"); - modeMenuController.activateEnterMovesMode(); + engineController.activateEnterMovesMode(gameModel); } }); @@ -768,7 +768,7 @@ btnFullAnalysis, new Separator(), // enter moves mode tglEngineOnOff.setSelected(false); tglEngineOnOff.setText("Off"); - modeMenuController.activateEnterMovesMode(); + engineController.activateEnterMovesMode(gameModel); } if(event.getCode() == KeyCode.F11) { stage.setFullScreen(true); @@ -969,7 +969,7 @@ private void handleNewGame() { modeMenuController.activatePlayBlackMode(); } } else { - modeMenuController.activateEnterMovesMode(); + engineController.activateEnterMovesMode(gameModel); } } } diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/Chessboard.java b/src/main/java/org/asdfjkl/jerryfx/gui/Chessboard.java index d6335aff..7572d74c 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/Chessboard.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/Chessboard.java @@ -32,7 +32,7 @@ import static org.asdfjkl.jerryfx.lib.CONSTANTS.*; -public class Chessboard extends Canvas implements StateChangeListener { +public class Chessboard extends CanvasProperties implements StateChangeListener { BoardStyle boardStyle; final double outputScaleX; @@ -89,49 +89,18 @@ public Chessboard(GameModel gameModel) { } - @Override - public boolean isResizable() { - return true; - } - - @Override - public double maxHeight(double width) { - return Double.POSITIVE_INFINITY; - } @Override - public double maxWidth(double height) { - return Double.POSITIVE_INFINITY; - } - - @Override - public double minWidth(double height) { - return 50D; - } - - @Override - public double minHeight(double width) { - return 50D; - } - - @Override - public void resize(double width, double height) { - this.setWidth(width); - this.setHeight(height); - - updateCanvas(); - } - public void updateCanvas() { - GraphicsContext gc = this.getGraphicsContext2D(); + GraphicsContext graphicsContext = this.getGraphicsContext2D(); // fill background - gc.beginPath(); + graphicsContext.beginPath(); //gc.setFill(Color.rgb(152, 152, 152)); - gc.setFill(boardStyle.getDarkSquareColor()); - gc.rect(0, 0, this.getWidth(), this.getHeight()); - gc.fill(); + graphicsContext.setFill(boardStyle.getDarkSquareColor()); + graphicsContext.rect(0, 0, this.getWidth(), this.getHeight()); + graphicsContext.fill(); // size of real board incl. corner double height = this.getHeight(); @@ -154,10 +123,10 @@ public void updateCanvas() { innerYOffset = (outerMargin + borderMargin); // paint board inc. margin with letters & numbers - gc.beginPath(); - gc.setFill(boardStyle.getBorderColor()); - gc.rect(xOffset, outerMargin, (squareSize*8)+(borderMargin*2), (squareSize*8)+(borderMargin*2)); - gc.fill(); + graphicsContext.beginPath(); + graphicsContext.setFill(boardStyle.getBorderColor()); + graphicsContext.rect(xOffset, outerMargin, (squareSize*8)+(borderMargin*2), (squareSize*8)+(borderMargin*2)); + graphicsContext.fill(); // get the from and to field of the last move // to highlight those squares @@ -193,10 +162,10 @@ public void updateCanvas() { } int y = (innerYOffset) + ((7-j)*squareSize); - gc.beginPath(); - gc.setFill(fieldColor); - gc.rect(x,y,squareSize,squareSize); - gc.fill(); + graphicsContext.beginPath(); + graphicsContext.setFill(fieldColor); + graphicsContext.rect(x,y,squareSize,squareSize); + graphicsContext.fill(); if(lastMoveFrom != null && lastMoveTo != null) { boolean markField = false; @@ -213,10 +182,10 @@ public void updateCanvas() { } } if(markField) { - gc.beginPath(); - gc.setFill(lastMoveColor); - gc.rect(x, y, squareSize, squareSize); - gc.fill(); + graphicsContext.beginPath(); + graphicsContext.setFill(lastMoveColor); + graphicsContext.rect(x, y, squareSize, squareSize); + graphicsContext.fill(); } } } @@ -225,41 +194,41 @@ public void updateCanvas() { // paint colored fields for(ColoredField coloredField : gameModel.getGame().getCurrentNode().getColoredFields()) { - int i = coloredField.x; - int j = coloredField.y; + int xColoredField = coloredField.x; + int yColoredField = coloredField.y; - int x = (innerXOffset) + (i*squareSize); - int y = (innerYOffset) + ((7-j)*squareSize); + int x = (innerXOffset) + (xColoredField*squareSize); + int y = (innerYOffset) + ((7-yColoredField)*squareSize); if(flipBoard) { - x = innerXOffset+((7-i)*squareSize); - y = (innerYOffset) + (j*squareSize); + x = innerXOffset+((7-xColoredField)*squareSize); + y = (innerYOffset) + (yColoredField*squareSize); } - gc.beginPath(); - gc.setFill(coloredFieldColor); - gc.rect(x,y,squareSize,squareSize); - gc.fill(); + graphicsContext.beginPath(); + graphicsContext.setFill(coloredFieldColor); + graphicsContext.rect(x,y,squareSize,squareSize); + graphicsContext.fill(); } // draw the board coordinates - gc.setFill(boardStyle.getCoordinateColor()); + graphicsContext.setFill(boardStyle.getCoordinateColor()); for(int i=0;i<8;i++) { if(flipBoard){ char ch = (char) (65 + (7 - i)); String idx = Character.toString(ch); String num = Integer.toString(i + 1); - gc.beginPath(); - gc.fillText(idx, innerXOffset + (i * squareSize) + (squareSize / 2) - 4, + graphicsContext.beginPath(); + graphicsContext.fillText(idx, innerXOffset + (i * squareSize) + (squareSize / 2) - 4, innerYOffset + (8 * squareSize) + (borderMargin * 0.8)); - gc.fillText(num, xOffset + 5, innerYOffset + (i * squareSize) + (squareSize / 2) + 4); + graphicsContext.fillText(num, xOffset + 5, innerYOffset + (i * squareSize) + (squareSize / 2) + 4); } else{ char ch = (char) (65 + i); String idx = Character.toString(ch); String num = Integer.toString(8 - i); - gc.beginPath(); - gc.fillText(idx, innerXOffset + (i * squareSize) + (squareSize / 2) - 4, + graphicsContext.beginPath(); + graphicsContext.fillText(idx, innerXOffset + (i * squareSize) + (squareSize / 2) - 4, innerYOffset + (8 * squareSize) + (borderMargin * 0.8)); - gc.fillText(num, xOffset + 5, innerYOffset + (i * squareSize) + (squareSize / 2) + 4); + graphicsContext.fillText(num, xOffset + 5, innerYOffset + (i * squareSize) + (squareSize / 2) + 4); } } @@ -287,13 +256,13 @@ public void updateCanvas() { if (!(drawGrabbedPiece && i == moveSource.x && j == moveSource.y)) { Image pieceImage = pieceImageProvider.getImage(piece, (int) (squareSize * this.outputScaleX), boardStyle.getPieceStyle()); - gc.drawImage(pieceImage, x, y, squareSize, squareSize); + graphicsContext.drawImage(pieceImage, x, y, squareSize, squareSize); } } else { if (!(drawGrabbedPiece && i == moveSource.x && (7-j) == moveSource.y)) { Image pieceImage = pieceImageProvider.getImage(piece, (int) (squareSize * this.outputScaleX), boardStyle.getPieceStyle()); - gc.drawImage(pieceImage, x, y, squareSize, squareSize); + graphicsContext.drawImage(pieceImage, x, y, squareSize, squareSize); } } } @@ -316,10 +285,10 @@ public void updateCanvas() { y_side_to_move = innerYOffset - 11; } } - gc.beginPath(); - gc.setFill(boardStyle.getLightSquareColor()); - gc.rect(x_side_to_move, y_side_to_move, 4,4); - gc.fill(); + graphicsContext.beginPath(); + graphicsContext.setFill(boardStyle.getLightSquareColor()); + graphicsContext.rect(x_side_to_move, y_side_to_move, 4,4); + graphicsContext.fill(); } // draw grabbed piece @@ -327,7 +296,7 @@ public void updateCanvas() { int offset = squareSize / 2; Image pieceImage = pieceImageProvider.getImage(grabbedPiece.getPiece(), (int) (squareSize * this.outputScaleX), boardStyle.getPieceStyle()); - gc.drawImage(pieceImage, grabbedPiece.getCurrentXLocation() - offset, + graphicsContext.drawImage(pieceImage, grabbedPiece.getCurrentXLocation() - offset, grabbedPiece.getCurrentYLocation() - offset,squareSize, squareSize); } diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/EngineController.java b/src/main/java/org/asdfjkl/jerryfx/gui/EngineController.java index 926827eb..4b092b15 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/EngineController.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/EngineController.java @@ -31,11 +31,11 @@ public class EngineController { EngineThread engineThread; final BlockingQueue cmdQueue = new LinkedBlockingQueue();; - ModeMenuController mmc = null; + ModeMenuController modeMenuController = null; public EngineController(ModeMenuController modeMenuController) { - mmc = modeMenuController; + this.modeMenuController = modeMenuController; } @@ -53,7 +53,7 @@ public void changed(final ObservableValue observable, @Override public void run() { String value = count.getAndSet(null); - mmc.handleEngineInfo(value); + modeMenuController.handleEngineInfo(value); } }); } @@ -122,5 +122,42 @@ public void uciGoMoveTime(int milliseconds) { } } + void restartGame(Boolean setUciLimitStrength, GameModel gameModel) { + if(gameModel.activeEngine.supportsUciLimitStrength()) { + gameModel.activeEngine.setUciLimitStrength(setUciLimitStrength); + } + sendCommand("stop"); + sendCommand("quit"); + String cmdEngine = gameModel.activeEngine.getPath(); + sendCommand("start "+cmdEngine); + sendCommand("uci"); + sendCommand("ucinewgame"); + } + + public void activateEnterMovesMode(GameModel gameModel) { + sendCommand("stop"); + sendCommand("quit"); + gameModel.setMode(GameModel.MODE_ENTER_MOVES); + gameModel.triggerStateChange(); + } + + void handleStateChangeAnalysis(GameModel gameModel) { + + String fen = gameModel.getGame().getCurrentNode().getBoard().fen(); + sendCommand("stop"); + sendCommand("position fen "+fen); + sendCommand("go infinite"); + + } + + void resetEngine(GameModel gameModel) { + restartGame(false, gameModel); + for(EngineOption enOpt : gameModel.activeEngine.options) { + if(enOpt.isNotDefault()) { + sendCommand(enOpt.toUciCommand()); + } + } + } + } diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/EnterPosBoard.java b/src/main/java/org/asdfjkl/jerryfx/gui/EnterPosBoard.java index fd3c4397..c8e10379 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/EnterPosBoard.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/EnterPosBoard.java @@ -33,7 +33,7 @@ import static org.asdfjkl.jerryfx.lib.CONSTANTS.EMPTY; import static org.asdfjkl.jerryfx.lib.CONSTANTS.FRINGE; -public class EnterPosBoard extends Canvas { +public class EnterPosBoard extends CanvasProperties { private final ArrayList enterPosBoardListeners = new ArrayList<>(); @@ -83,21 +83,6 @@ public EnterPosBoard(Board board) { } - @Override - public boolean isResizable() { - return true; - } - - @Override - public double maxHeight(double width) { - return Double.POSITIVE_INFINITY; - } - - @Override - public double maxWidth(double height) { - return Double.POSITIVE_INFINITY; - } - @Override public double minWidth(double height) { return Math.max(this.getHeight() * 1.5,150D); @@ -108,13 +93,6 @@ public double minHeight(double width) { return 80D; } - @Override - public void resize(double width, double height) { - this.setWidth(width); - this.setHeight(height); - - updateCanvas(); - } boolean clickedOnBoard(double x, double y) { @@ -139,6 +117,7 @@ boolean clickedOnPieceSelector(double x, double y) { } } + @Override public void updateCanvas() { GraphicsContext gc = this.getGraphicsContext2D(); diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/GameMenuController.java b/src/main/java/org/asdfjkl/jerryfx/gui/GameMenuController.java index 8a6884a8..e3b0c10e 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/GameMenuController.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/GameMenuController.java @@ -119,39 +119,31 @@ public void handleOpenGame() { return; } } else { // indices > 1, show db dialog - DialogDatabase dlg = new DialogDatabase(); - gameModel.getPgnDatabase().filename = file.getAbsolutePath(); - //gameModel.getPgnDatabase().open(file.getAbsolutePath()); - boolean accepted = dlg.show(gameModel, true); - if(accepted) { - int gameIndex = dlg.table.getSelectionModel().getSelectedIndex(); - gameModel.currentPgnDatabaseIdx = gameIndex; - Game g = gameModel.getPgnDatabase().loadGame(gameIndex); - gameModel.setGame(g); - g.setHeaderWasChanged(true); - g.setTreeWasChanged(true); - gameModel.triggerStateChange(); - } + showDbDialog(file); } } else { // for larger files, we always assume there is more than one game // then show database dialog - DialogDatabase dlg = new DialogDatabase(); - gameModel.getPgnDatabase().filename = file.getAbsolutePath(); - //gameModel.getPgnDatabase().open(file.getAbsolutePath()); - boolean accepted = dlg.show(gameModel, true); - if(accepted) { - int gameIndex = dlg.table.getSelectionModel().getSelectedIndex(); - gameModel.currentPgnDatabaseIdx = gameIndex; - Game g = gameModel.getPgnDatabase().loadGame(gameIndex); - gameModel.setGame(g); - g.setHeaderWasChanged(true); - g.setTreeWasChanged(true); - gameModel.triggerStateChange(); - } + showDbDialog(file); } } } + private void showDbDialog(File file) { + DialogDatabase dlg = new DialogDatabase(); + gameModel.getPgnDatabase().filename = file.getAbsolutePath(); + //gameModel.getPgnDatabase().open(file.getAbsolutePath()); + boolean accepted = dlg.show(gameModel, true); + if(accepted) { + int gameIndex = dlg.table.getSelectionModel().getSelectedIndex(); + gameModel.currentPgnDatabaseIdx = gameIndex; + Game g = gameModel.getPgnDatabase().loadGame(gameIndex); + gameModel.setGame(g); + g.setHeaderWasChanged(true); + g.setTreeWasChanged(true); + gameModel.triggerStateChange(); + } + } + public void handleSaveCurrentGame() { DialogSave dlg = new DialogSave(); diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/GameModel.java b/src/main/java/org/asdfjkl/jerryfx/gui/GameModel.java index b5503b47..b238dcca 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/GameModel.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/GameModel.java @@ -90,6 +90,8 @@ public class GameModel { BoardStyle boardStyle; public GameModel() { + + FilePath filePath = new FilePath(); this.game = new Game(); Board b = new Board(true); @@ -101,8 +103,8 @@ public GameModel() { this.game.getRootNode().setBoard(b); this.currentMode = MODE_ENTER_MOVES; - String stockfishPath = getStockfishPath(); - String bookPath = getBookPath(); + String stockfishPath = filePath.getStockfishPath(); + String bookPath = filePath.getBookPath(); Engine stockfish = new Engine(); stockfish.setName("Stockfish (Internal)"); @@ -124,7 +126,7 @@ public GameModel() { File file = null; extBook = new PolyglotExt(); - String extBookPath = getExtBookPath(); + String extBookPath = filePath.getExtBookPath(); if(extBookPath != null) { file = new File(extBookPath); extBook.loadBook(file); @@ -132,99 +134,6 @@ public GameModel() { } - private String getStockfishPath() { - - String os = System.getProperty("os.name").toLowerCase(); - //System.out.println(os); - if(os.contains("win")) { - - String stockfishPath = ""; - String jarPath = ""; - String path = App.class.getProtectionDomain().getCodeSource().getLocation().getPath(); - jarPath = URLDecoder.decode(path, StandardCharsets.UTF_8); - File tmp = (new File(jarPath)); - if(tmp.getParentFile().exists()) { - File subEngine = new File(tmp.getParentFile(), "engine"); - stockfishPath = new File(subEngine, "stockfish_14.1.exe").getPath(); - return stockfishPath; - } - } - if(os.contains("linux")) { - String stockfishPath = ""; - String jarPath = ""; - String path = App.class.getProtectionDomain().getCodeSource().getLocation().getPath(); - //System.out.println(path); - jarPath = URLDecoder.decode(path, StandardCharsets.UTF_8); - //System.out.println(jarPath); - File tmp = (new File(jarPath)); - if(tmp.getParentFile().exists()) { - //System.out.println(tmp.getParentFile().getAbsolutePath()); - if(tmp.getParentFile().getParentFile().exists()) { - File subEngine = new File(tmp.getParentFile().getParentFile(), "engine"); - //System.out.println(subEngine.getPath()); - stockfishPath = new File(subEngine, "stockfish_x64").getPath(); - return stockfishPath; - } - } - - } - return null; - } - - private File getBaseBookPath() { - String os = System.getProperty("os.name").toLowerCase(); - if(os.contains("win")) { - String jarPath = ""; - String path = App.class.getProtectionDomain().getCodeSource().getLocation().getPath(); - jarPath = URLDecoder.decode(path, StandardCharsets.UTF_8); - File tmp = (new File(jarPath)); - if(tmp.getParentFile().exists()) { - File subBook = new File(tmp.getParentFile(), "book"); - return subBook; - //bookPath = new File(subBook, "varied.bin").getPath(); - //return bookPath; - } - } - if(os.contains("linux")) { - String jarPath = ""; - String path = App.class.getProtectionDomain().getCodeSource().getLocation().getPath(); - jarPath = URLDecoder.decode(path, StandardCharsets.UTF_8); - File tmp = (new File(jarPath)); - if(tmp.getParentFile().exists()) { - if(tmp.getParentFile().getParentFile().exists()) { - File subBook = new File(tmp.getParentFile().getParentFile(), "book"); - return subBook; - //bookPath = new File(subBook, "varied.bin").getPath(); - //return bookPath; - } - } - } - return null; - } - - private String getBookPath() { - File baseBook = getBaseBookPath(); - if(baseBook != null) { - String bookPath = new File(baseBook, "varied.bin").getPath(); - return bookPath; - } - return null; - } - - private String getExtBookPath() { - - return "C:\\Users\\user\\MyFiles\\workspace\\extbook\\extbook.bin"; - - /* - File baseBook = getBaseBookPath(); - if(baseBook != null) { - String bookPath = new File(baseBook, "extbook.bin").getPath(); - return bookPath; - } - return null; -*/ - } - public Game getGame() { return game; } diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/ModeMenuController.java b/src/main/java/org/asdfjkl/jerryfx/gui/ModeMenuController.java index fd41d1b2..04c53cd7 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/ModeMenuController.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/ModeMenuController.java @@ -42,20 +42,20 @@ public ModeMenuController(GameModel gameModel, EngineOutputView engineOutputView this.engineOutputView = engineOutputView; } - public void handleEngineInfo(String s) { + public void handleEngineInfo(String value) { - if(s.startsWith("INFO")) { + if(value.startsWith("INFO")) { //"INFO |Stockfish 12 (Level MAX)|zobrist|145.081 kn/s||(#0) 23. Be7#||||" - String[] sSplit = s.split("\\|"); - if(gameModel.getGame().getCurrentNode().getBoard().isCheckmate() && sSplit.length > 1) { - String sTemp = "|" + sSplit[1] + "||||(#0)|"; - this.engineOutputView.setText(sTemp); + String[] valueSplit = value.split("\\|"); + if(gameModel.getGame().getCurrentNode().getBoard().isCheckmate() && valueSplit.length > 1) { + String outputViewValue = "|" + valueSplit[1] + "||||(#0)|"; + this.engineOutputView.setText(outputViewValue); } else { - this.engineOutputView.setText(s.substring(5)); + this.engineOutputView.setText(value.substring(5)); } } - if(s.startsWith("BESTMOVE")) { - handleBestMove(s); + if(value.startsWith("BESTMOVE")) { + handleBestMove(value); } } @@ -66,20 +66,7 @@ public void setEngineController(EngineController engineController) { public void activateAnalysisMode() { // first change gamestate and reset engine - if(gameModel.activeEngine.supportsUciLimitStrength()) { - gameModel.activeEngine.setUciLimitStrength(false); - } - engineController.sendCommand("stop"); - engineController.sendCommand("quit"); - String cmdEngine = gameModel.activeEngine.getPath(); - engineController.sendCommand("start "+cmdEngine); - engineController.sendCommand("uci"); - engineController.sendCommand("ucinewgame"); - for(EngineOption enOpt : gameModel.activeEngine.options) { - if(enOpt.isNotDefault()) { - engineController.sendCommand(enOpt.toUciCommand()); - } - } + engineController.resetEngine(gameModel); if(gameModel.activeEngine.supportsMultiPV()) { engineController.sendCommand("setoption name MultiPV value " + gameModel.getMultiPv()); } @@ -87,22 +74,6 @@ public void activateAnalysisMode() { gameModel.triggerStateChange(); } - public void activateEnterMovesMode() { - engineController.sendCommand("stop"); - engineController.sendCommand("quit"); - gameModel.setMode(GameModel.MODE_ENTER_MOVES); - gameModel.triggerStateChange(); - } - - private void handleStateChangeAnalysis() { - - String fen = gameModel.getGame().getCurrentNode().getBoard().fen(); - engineController.sendCommand("stop"); - engineController.sendCommand("position fen "+fen); - engineController.sendCommand("go infinite"); - - } - private void handleStateChangeGameAnalysis() { boolean continueAnalysis = true; @@ -135,7 +106,7 @@ private void handleStateChangeGameAnalysis() { if(!continueAnalysis) { // we are at the root or found a book move gameModel.getGame().setTreeWasChanged(true); - activateEnterMovesMode(); + engineController.activateEnterMovesMode(gameModel); //FlatAlert alert = new FlatAlert(Alert.AlertType.INFORMATION); FlatAlert alert = new FlatAlert(Alert.AlertType.INFORMATION); @@ -156,18 +127,10 @@ private void handleStateChangeGameAnalysis() { public void activatePlayWhiteMode() { // first change gamestate and reset engine - if(gameModel.activeEngine.supportsUciLimitStrength()) { - gameModel.activeEngine.setUciLimitStrength(true); - } - engineController.sendCommand("stop"); - engineController.sendCommand("quit"); - String cmdEngine = gameModel.activeEngine.getPath(); - engineController.sendCommand("start "+cmdEngine); - engineController.sendCommand("uci"); - engineController.sendCommand("ucinewgame"); - for(EngineOption enOpt : gameModel.activeEngine.options) { - if(enOpt.isNotDefault()) { - engineController.sendCommand(enOpt.toUciCommand()); + engineController.restartGame(true, gameModel); + for(EngineOption engineOption : gameModel.activeEngine.options) { + if(engineOption.isNotDefault()) { + engineController.sendCommand(engineOption.toUciCommand()); } } if(gameModel.activeEngine.isInternal()) { @@ -209,20 +172,7 @@ public void activatePlayBlackMode() { public void activatePlayoutPositionMode() { // first change gamestate and reset engine - if(gameModel.activeEngine.supportsUciLimitStrength()) { - gameModel.activeEngine.setUciLimitStrength(false); - } - engineController.sendCommand("stop"); - engineController.sendCommand("quit"); - String cmdEngine = gameModel.activeEngine.getPath(); - engineController.sendCommand("start "+cmdEngine); - engineController.sendCommand("uci"); - engineController.sendCommand("ucinewgame"); - for(EngineOption enOpt : gameModel.activeEngine.options) { - if(enOpt.isNotDefault()) { - engineController.sendCommand(enOpt.toUciCommand()); - } - } + engineController.resetEngine(gameModel); // trigger statechange gameModel.setMode(GameModel.MODE_PLAYOUT_POSITION); gameModel.setFlipBoard(false); @@ -236,15 +186,7 @@ public void activateGameAnalysisMode() { gameModel.getGame().removeAllAnnotations(); gameModel.getGame().setTreeWasChanged(true); - if(gameModel.activeEngine.supportsUciLimitStrength()) { - gameModel.activeEngine.setUciLimitStrength(false); - } - engineController.sendCommand("stop"); - engineController.sendCommand("quit"); - String cmdEngine = gameModel.activeEngine.getPath(); - engineController.sendCommand("start "+cmdEngine); - engineController.sendCommand("uci"); - engineController.sendCommand("ucinewgame"); + engineController.restartGame(false, gameModel); if(gameModel.activeEngine.supportsMultiPV()) { engineController.sendCommand("setoption name MultiPV value 1"); } @@ -338,12 +280,12 @@ private void addBestPv(String[] uciMoves) { try { GameNode next = new GameNode(); Board board = currentNode.getBoard().makeCopy(); - Move m = new Move(uciMove); - if(!board.isLegal(m)) { + Move move = new Move(uciMove); + if(!board.isLegal(move)) { break; } - board.apply(m); - next.setMove(m); + board.apply(move); + next.setMove(move); next.setBoard(board); next.setParent(currentNode); // to avoid bugs when incoherent information is @@ -410,13 +352,13 @@ public void handleBestMove(String bestmove) { // todo: catch Exceptions! String uci = bestmoveItems[1].split(" ")[0]; Move m = new Move(uci); - Board b = gameModel.getGame().getCurrentNode().getBoard(); - if (b.isLegal(m)) { - if(mode == GameModel.MODE_PLAY_WHITE && b.turn == CONSTANTS.BLACK) { + Board board = gameModel.getGame().getCurrentNode().getBoard(); + if (board.isLegal(m)) { + if(mode == GameModel.MODE_PLAY_WHITE && board.turn == CONSTANTS.BLACK) { gameModel.getGame().applyMove(m); gameModel.triggerStateChange(); } - if(mode == GameModel.MODE_PLAY_BLACK && b.turn == CONSTANTS.WHITE) { + if(mode == GameModel.MODE_PLAY_BLACK && board.turn == CONSTANTS.WHITE) { gameModel.getGame().applyMove(m); gameModel.triggerStateChange(); } @@ -484,19 +426,13 @@ public void handleBestMove(String bestmove) { addBestPv(pvMoves); - NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH); - DecimalFormat decim = (DecimalFormat) nf; - decim.applyPattern("0.00"); - String sCurrentBest = decim.format(gameModel.currentBestEval / 100.0); - String sChildBest = decim.format(gameModel.childBestEval / 100.0); - - ArrayList vars = gameModel.getGame().getCurrentNode().getVariations(); - if (vars != null && vars.size() > 1) { - GameNode child0 = gameModel.getGame().getCurrentNode().getVariation(0); - child0.setComment(sChildBest); - GameNode child1 = gameModel.getGame().getCurrentNode().getVariation(1); - child1.setComment(sCurrentBest); - } + NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH); + DecimalFormat decimalFormat = (DecimalFormat) numberFormat; + decimalFormat.applyPattern("0.00"); + String currentBest = decimalFormat.format(gameModel.currentBestEval / 100.0); + String childBest = decimalFormat.format(gameModel.childBestEval / 100.0); + + setGameBestComments(currentBest, childBest); } } } @@ -509,22 +445,16 @@ public void handleBestMove(String bestmove) { NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH); DecimalFormat decim = (DecimalFormat) nf; decim.applyPattern("0.00"); - String sChildBest = decim.format(gameModel.childBestEval / 100.0); + String childBest = decim.format(gameModel.childBestEval / 100.0); - String sCurrentBest = ""; + String currentBest = ""; if (turn == CONSTANTS.WHITE) { - sCurrentBest = "#" + (Math.abs(gameModel.currentMateInMoves)); + currentBest = "#" + (Math.abs(gameModel.currentMateInMoves)); } else { - sCurrentBest = "#-" + (Math.abs(gameModel.currentMateInMoves)); + currentBest = "#-" + (Math.abs(gameModel.currentMateInMoves)); } - ArrayList vars = gameModel.getGame().getCurrentNode().getVariations(); - if (vars != null && vars.size() > 1) { - GameNode child0 = gameModel.getGame().getCurrentNode().getVariation(0); - child0.setComment(sChildBest); - GameNode child1 = gameModel.getGame().getCurrentNode().getVariation(1); - child1.setComment(sCurrentBest); - } + setGameBestComments(currentBest, childBest); } if (!gameModel.currentIsMate && gameModel.childIsMate) { @@ -535,22 +465,16 @@ public void handleBestMove(String bestmove) { NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH); DecimalFormat decim = (DecimalFormat) nf; decim.applyPattern("0.00"); - String sCurrentBest = decim.format(gameModel.currentBestEval / 100.0); + String currentBest = decim.format(gameModel.currentBestEval / 100.0); - String sChildBest = ""; + String childBest = ""; if (turn == CONSTANTS.WHITE) { - sChildBest = "#-" + (Math.abs(gameModel.childMateInMoves)); + childBest = "#-" + (Math.abs(gameModel.childMateInMoves)); } else { - sChildBest = "#" + (Math.abs(gameModel.childMateInMoves)); + childBest = "#" + (Math.abs(gameModel.childMateInMoves)); } - ArrayList vars = gameModel.getGame().getCurrentNode().getVariations(); - if (vars != null && vars.size() > 1) { - GameNode child0 = gameModel.getGame().getCurrentNode().getVariation(0); - child0.setComment(sChildBest); - GameNode child1 = gameModel.getGame().getCurrentNode().getVariation(1); - child1.setComment(sCurrentBest); - } + setGameBestComments(currentBest, childBest); } if (gameModel.currentIsMate && gameModel.childIsMate) { @@ -562,23 +486,17 @@ public void handleBestMove(String bestmove) { String[] pvMoves = gameModel.currentBestPv.split(" "); addBestPv(pvMoves); - String sCurrentBest = ""; - String sChildBest = ""; + String currentBest = ""; + String childBest = ""; if (turn == CONSTANTS.WHITE) { - sCurrentBest = "#" + (Math.abs(gameModel.currentMateInMoves)); - sChildBest = "#-" + (Math.abs(gameModel.childMateInMoves)); + currentBest = "#" + (Math.abs(gameModel.currentMateInMoves)); + childBest = "#-" + (Math.abs(gameModel.childMateInMoves)); } else { - sCurrentBest = "#-" + (Math.abs(gameModel.currentMateInMoves)); - sChildBest = "#" + (Math.abs(gameModel.childMateInMoves)); + currentBest = "#-" + (Math.abs(gameModel.currentMateInMoves)); + childBest = "#" + (Math.abs(gameModel.childMateInMoves)); } - ArrayList vars = gameModel.getGame().getCurrentNode().getVariations(); - if (vars != null && vars.size() > 1) { - GameNode child0 = gameModel.getGame().getCurrentNode().getVariation(0); - child0.setComment(sChildBest); - GameNode child1 = gameModel.getGame().getCurrentNode().getVariation(1); - child1.setComment(sCurrentBest); - } + setGameBestComments(currentBest, childBest); } } } @@ -589,6 +507,16 @@ public void handleBestMove(String bestmove) { } + private void setGameBestComments(String currentBest, String childBest) { + ArrayList vars = gameModel.getGame().getCurrentNode().getVariations(); + if (vars != null && vars.size() > 1) { + GameNode child0 = gameModel.getGame().getCurrentNode().getVariation(0); + child0.setComment(childBest); + GameNode child1 = gameModel.getGame().getCurrentNode().getVariation(1); + child1.setComment(currentBest); + } + } + @Override public void stateChange() { int mode = gameModel.getMode(); @@ -653,7 +581,7 @@ public void stateChange() { } else { gameModel.doNotNotifyAboutResult = false; if (mode == GameModel.MODE_ANALYSIS) { - handleStateChangeAnalysis(); + engineController.handleStateChangeAnalysis(gameModel); } if (mode == GameModel.MODE_GAME_ANALYSIS) { handleStateChangeGameAnalysis(); diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/PgnDatabase.java b/src/main/java/org/asdfjkl/jerryfx/gui/PgnDatabase.java index c790b896..74b99ebf 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/PgnDatabase.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/PgnDatabase.java @@ -31,7 +31,6 @@ import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; -import javafx.util.Pair; import jfxtras.styles.jmetro.JMetro; import org.asdfjkl.jerryfx.lib.*; @@ -123,7 +122,7 @@ public void saveDatabase() { public void saveDatabaseAs(String filename) { - String tmpFilenameWoDir = Util.getRandomFilename(); + String tmpFilenameWoDir = RandomFileNameGenerator.getRandomFilename(); File file = new File(filename); File path = file.getParentFile(); @@ -138,27 +137,7 @@ public void saveDatabaseAs(String filename) { final ObservableList entries = this.entries; - stage = new Stage(); - stage.initModality(Modality.APPLICATION_MODAL); - stage.initStyle(StageStyle.UNDECORATED); - - Label lblScanPgn = new Label("Saving PGN..."); - ProgressBar progressBar = new ProgressBar(); - - VBox vbox = new VBox(); - vbox.setAlignment(Pos.CENTER); - vbox.getChildren().addAll(lblScanPgn, progressBar); - - vbox.setSpacing(10); - vbox.setPadding( new Insets(10)); - - Scene scene = new Scene(vbox, 400, 200); - - JMetro jMetro = new JMetro(); - jMetro.setScene(scene); - - stage.setScene(scene); - stage.show(); + ProgressBar progressBar = getProgressBar("Saving PGN..."); Task task = new Task<>() { @Override protected Void call() throws Exception { @@ -340,15 +319,10 @@ public void appendToCurrentPGN(Game g) { public void appendToOtherPGN(GameModel gameModel) { // write game to file, then re-load this file into database - FileChooser fileChooser = new FileChooser(); + Stage stage = new Stage(); stage.initModality(Modality.APPLICATION_MODAL); - if(gameModel.lastSaveDirPath != null && gameModel.lastSaveDirPath.exists()) { - fileChooser.setInitialDirectory(gameModel.lastSaveDirPath); - } - fileChooser.getExtensionFilters().addAll( - new FileChooser.ExtensionFilter("PGN", "*.pgn") - ); + FileChooser fileChooser = getFileChooser(gameModel); File file = fileChooser.showOpenDialog(stage); if (file != null) { if(file.getParentFile() != null) { @@ -390,15 +364,10 @@ public void replaceCurrentGame(Game g, int currentDatabaseIndex) { public void saveAsNewPGN(GameModel gameModel) { // write game to file, then re-load this file into database - FileChooser fileChooser = new FileChooser(); + Stage stage = new Stage(); stage.initModality(Modality.APPLICATION_MODAL); - if(gameModel.lastSaveDirPath != null && gameModel.lastSaveDirPath.exists()) { - fileChooser.setInitialDirectory(gameModel.lastSaveDirPath); - } - fileChooser.getExtensionFilters().addAll( - new FileChooser.ExtensionFilter("PGN", "*.pgn") - ); + FileChooser fileChooser = getFileChooser(gameModel); File file = fileChooser.showSaveDialog(stage); if (file != null) { if(file.getParentFile() != null) { @@ -414,9 +383,20 @@ public void saveAsNewPGN(GameModel gameModel) { } + private FileChooser getFileChooser(GameModel gameModel) { + FileChooser fileChooser = new FileChooser(); + if(gameModel.lastSaveDirPath != null && gameModel.lastSaveDirPath.exists()) { + fileChooser.setInitialDirectory(gameModel.lastSaveDirPath); + } + fileChooser.getExtensionFilters().addAll( + new FileChooser.ExtensionFilter("PGN", "*.pgn") + ); + return fileChooser; + } + public void deleteGame(int index) { - String tmpFilenameWoDir = Util.getRandomFilename(); + String tmpFilenameWoDir = RandomFileNameGenerator.getRandomFilename(); File file = new File(filename); File path = file.getParentFile(); @@ -431,27 +411,7 @@ public void deleteGame(int index) { final ObservableList entries = this.entries; - stage = new Stage(); - stage.initModality(Modality.APPLICATION_MODAL); - stage.initStyle(StageStyle.UNDECORATED); - - Label lblScanPgn = new Label("Deleting Game..."); - ProgressBar progressBar = new ProgressBar(); - - VBox vbox = new VBox(); - vbox.setAlignment(Pos.CENTER); - vbox.getChildren().addAll(lblScanPgn, progressBar); - - vbox.setSpacing(10); - vbox.setPadding( new Insets(10)); - - Scene scene = new Scene(vbox, 400, 200); - - JMetro jMetro = new JMetro(); - jMetro.setScene(scene); - - stage.setScene(scene); - stage.show(); + ProgressBar progressBar = getProgressBar("Deleting Game..."); Task task = new Task<>() { @Override protected Void call() throws Exception { @@ -579,13 +539,12 @@ public void deleteGame(int index) { } - public void open() { - + private ProgressBar getProgressBar(String label) { stage = new Stage(); stage.initModality(Modality.APPLICATION_MODAL); stage.initStyle(StageStyle.UNDECORATED); - Label lblScanPgn = new Label("Scanning PGN..."); + Label lblScanPgn = new Label(label); ProgressBar progressBar = new ProgressBar(); VBox vbox = new VBox(); @@ -602,6 +561,12 @@ public void open() { stage.setScene(scene); stage.show(); + return progressBar; + } + + public void open() { + + ProgressBar progressBar = getProgressBar("Scanning PGN..."); if(reader.isIsoLatin1(filename)) { reader.setEncodingIsoLatin1(); @@ -757,27 +722,7 @@ public void open() { public void search(SearchPattern pattern) { - stage = new Stage(); - stage.initModality(Modality.APPLICATION_MODAL); - stage.initStyle(StageStyle.UNDECORATED); - - Label lblScanPgn = new Label("Searching..."); - ProgressBar progressBar = new ProgressBar(); - - VBox vbox = new VBox(); - vbox.setAlignment(Pos.CENTER); - vbox.getChildren().addAll(lblScanPgn, progressBar); - - vbox.setSpacing(10); - vbox.setPadding( new Insets(10)); - - Scene scene = new Scene(vbox, 400, 200); - - JMetro jMetro = new JMetro(); - jMetro.setScene(scene); - - stage.setScene(scene); - stage.show(); + ProgressBar progressBar = getProgressBar("Searching..."); Task> task = new Task<>() { @@ -854,6 +799,4 @@ public void search(SearchPattern pattern) { } - - } diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/PieceImageProvider.java b/src/main/java/org/asdfjkl/jerryfx/gui/PieceImageProvider.java index 8f4be313..0b23ab4f 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/PieceImageProvider.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/PieceImageProvider.java @@ -92,23 +92,23 @@ private BufferedImage renderSVG(URL urlPieceSVG, int width, int height) { SVGUniverse svgUniverse = new SVGUniverse(); SVGDiagram diagram = null; - BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); try { diagram = svgUniverse.getDiagram(svgUniverse.loadSVG(urlPieceSVG)); diagram.setIgnoringClipHeuristic(true); - AffineTransform at = new AffineTransform(); - at.setToScale(width/diagram.getWidth(), height/diagram.getWidth()); - Graphics2D ig2 = bi.createGraphics(); - ig2.transform(at); - ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - diagram.render(ig2); + AffineTransform affineTransform = new AffineTransform(); + affineTransform.setToScale(width/diagram.getWidth(), height/diagram.getWidth()); + Graphics2D graphics2DImg = bufferedImage.createGraphics(); + graphics2DImg.transform(affineTransform); + graphics2DImg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + diagram.render(graphics2DImg); } catch (SVGException e) { e.printStackTrace(); } - return bi; + return bufferedImage; } - private HashMap getHashMap(int pieceType, int pieceStyle) { + private HashMap getPieceStyleHashMap(int pieceType, int pieceStyle) { if(pieceType == CONSTANTS.WHITE_PAWN) { if(pieceStyle == PIECE_STYLE_MERIDA) { return whitePawnsMerida; @@ -246,66 +246,66 @@ private HashMap getHashMap(int pieceType, int pieceStyle) { private String getFilename(int pieceType) { - if(pieceType == CONSTANTS.WHITE_PAWN) { - return "wp.svg"; - } - if(pieceType == CONSTANTS.BLACK_PAWN) { - return "bp.svg"; - } - if(pieceType == CONSTANTS.WHITE_ROOK) { - return "wr.svg"; - } - if(pieceType == CONSTANTS.BLACK_ROOK) { - return "br.svg"; - } - if(pieceType == CONSTANTS.WHITE_KNIGHT) { - return "wn.svg"; - } - if(pieceType == CONSTANTS.BLACK_KNIGHT) { - return "bn.svg"; - } - if(pieceType == CONSTANTS.WHITE_BISHOP) { - return "wb.svg"; - } - if(pieceType == CONSTANTS.BLACK_BISHOP) { - return "bb.svg"; - } - if(pieceType == CONSTANTS.WHITE_QUEEN) { - return "wq.svg"; - } - if(pieceType == CONSTANTS.BLACK_QUEEN) { - return "bq.svg"; - } - if(pieceType == CONSTANTS.WHITE_KING) { - return "wk.svg"; - } - if(pieceType == CONSTANTS.BLACK_KING) { - return "bk.svg"; - } - throw new IllegalArgumentException("called with, but there is no such piece: "+pieceType); + if(pieceType == CONSTANTS.WHITE_PAWN) { + return "wp.svg"; + } + if(pieceType == CONSTANTS.BLACK_PAWN) { + return "bp.svg"; + } + if(pieceType == CONSTANTS.WHITE_ROOK) { + return "wr.svg"; + } + if(pieceType == CONSTANTS.BLACK_ROOK) { + return "br.svg"; + } + if(pieceType == CONSTANTS.WHITE_KNIGHT) { + return "wn.svg"; + } + if(pieceType == CONSTANTS.BLACK_KNIGHT) { + return "bn.svg"; + } + if(pieceType == CONSTANTS.WHITE_BISHOP) { + return "wb.svg"; + } + if(pieceType == CONSTANTS.BLACK_BISHOP) { + return "bb.svg"; + } + if(pieceType == CONSTANTS.WHITE_QUEEN) { + return "wq.svg"; + } + if(pieceType == CONSTANTS.BLACK_QUEEN) { + return "bq.svg"; + } + if(pieceType == CONSTANTS.WHITE_KING) { + return "wk.svg"; + } + if(pieceType == CONSTANTS.BLACK_KING) { + return "bk.svg"; + } + throw new IllegalArgumentException("called with, but there is no such piece: "+pieceType); } public Image getImage(int piece, int squareSize, int pieceStyle) { - HashMap pieceHashMap = getHashMap(piece, pieceStyle); + HashMap pieceHashMap = getPieceStyleHashMap(piece, pieceStyle); String svgPieceName = getFilename(piece); if(pieceHashMap.containsKey(squareSize)) { return pieceHashMap.get(squareSize); } else { - String fn = "pieces/"; + String fileName = "pieces/"; if(pieceStyle == PIECE_STYLE_MERIDA) { - fn += "merida/"; + fileName += "merida/"; } if(pieceStyle == PIECE_STYLE_OLD) { - fn += "old/"; + fileName += "old/"; } if(pieceStyle == PIECE_STYLE_USCF) { - fn += "uscf/"; + fileName += "uscf/"; } - fn += svgPieceName; - URL urlSVG = getClass().getClassLoader().getResource(fn); + fileName += svgPieceName; + URL urlSVG = getClass().getClassLoader().getResource(fileName); BufferedImage bufferedImagePiece = renderSVG(urlSVG, squareSize, squareSize); Image img = SwingFXUtils.toFXImage(bufferedImagePiece, null); pieceHashMap.put(squareSize, img); diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/Util.java b/src/main/java/org/asdfjkl/jerryfx/gui/RandomFileNameGenerator.java similarity index 92% rename from src/main/java/org/asdfjkl/jerryfx/gui/Util.java rename to src/main/java/org/asdfjkl/jerryfx/gui/RandomFileNameGenerator.java index eea8774a..b425b6e5 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/Util.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/RandomFileNameGenerator.java @@ -3,7 +3,7 @@ import java.util.Date; import java.util.Random; -public class Util { +public class RandomFileNameGenerator { public static String getRandomFilename() { diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/ShowAppearanceBoard.java b/src/main/java/org/asdfjkl/jerryfx/gui/ShowAppearanceBoard.java index 0a2aeb1b..80dd1b8a 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/ShowAppearanceBoard.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/ShowAppearanceBoard.java @@ -28,7 +28,7 @@ import static org.asdfjkl.jerryfx.lib.CONSTANTS.EMPTY; import static org.asdfjkl.jerryfx.lib.CONSTANTS.FRINGE; -public class ShowAppearanceBoard extends Canvas { +public class ShowAppearanceBoard extends CanvasProperties { final BoardStyle boardStyle; final double outputScaleX; @@ -55,41 +55,8 @@ public ShowAppearanceBoard() { } - - @Override - public boolean isResizable() { - return true; - } - - @Override - public double maxHeight(double width) { - return Double.POSITIVE_INFINITY; - } - - @Override - public double maxWidth(double height) { - return Double.POSITIVE_INFINITY; - } - - @Override - public double minWidth(double height) { - return 50D; - } - - @Override - public double minHeight(double width) { - return 50D; - } - - @Override - public void resize(double width, double height) { - this.setWidth(width); - this.setHeight(height); - - updateCanvas(); - } - - public void updateCanvas() { + @Override + public void updateCanvas() { GraphicsContext gc = this.getGraphicsContext2D(); From 25c511fafb8034a9dfaa062e793f49411260c70e Mon Sep 17 00:00:00 2001 From: Manali Shah Date: Fri, 25 Mar 2022 17:54:54 -0300 Subject: [PATCH 2/4] Refactoring code - Extract class & pull-up method --- .../asdfjkl/jerryfx/gui/CanvasProperties.java | 39 +++++++ .../org/asdfjkl/jerryfx/gui/FilePath.java | 100 ++++++++++++++++++ 2 files changed, 139 insertions(+) create mode 100644 src/main/java/org/asdfjkl/jerryfx/gui/CanvasProperties.java create mode 100644 src/main/java/org/asdfjkl/jerryfx/gui/FilePath.java diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/CanvasProperties.java b/src/main/java/org/asdfjkl/jerryfx/gui/CanvasProperties.java new file mode 100644 index 00000000..366132d8 --- /dev/null +++ b/src/main/java/org/asdfjkl/jerryfx/gui/CanvasProperties.java @@ -0,0 +1,39 @@ +package org.asdfjkl.jerryfx.gui; + +import javafx.scene.canvas.Canvas; + +public abstract class CanvasProperties extends Canvas { + @Override + public boolean isResizable() { + return true; + } + + @Override + public double maxHeight(double width) { + return Double.POSITIVE_INFINITY; + } + + @Override + public double maxWidth(double height) { + return Double.POSITIVE_INFINITY; + } + + @Override + public double minWidth(double height) { + return 50D; + } + + @Override + public double minHeight(double width) { + return 50D; + } + + public void resize(double width, double height) { + this.setWidth(width); + this.setHeight(height); + + updateCanvas(); + } + + public void updateCanvas() {} +} diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/FilePath.java b/src/main/java/org/asdfjkl/jerryfx/gui/FilePath.java new file mode 100644 index 00000000..52789df2 --- /dev/null +++ b/src/main/java/org/asdfjkl/jerryfx/gui/FilePath.java @@ -0,0 +1,100 @@ +package org.asdfjkl.jerryfx.gui; + +import java.io.File; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; + +public class FilePath { + private File getBaseBookPath() { + String os = System.getProperty("os.name").toLowerCase(); + if(os.contains("win")) { + String jarPath = ""; + String path = App.class.getProtectionDomain().getCodeSource().getLocation().getPath(); + jarPath = URLDecoder.decode(path, StandardCharsets.UTF_8); + File tmp = (new File(jarPath)); + if(tmp.getParentFile().exists()) { + File subBook = new File(tmp.getParentFile(), "book"); + return subBook; + //bookPath = new File(subBook, "varied.bin").getPath(); + //return bookPath; + } + } + if(os.contains("linux")) { + String jarPath = ""; + String path = App.class.getProtectionDomain().getCodeSource().getLocation().getPath(); + jarPath = URLDecoder.decode(path, StandardCharsets.UTF_8); + File tmp = (new File(jarPath)); + if(tmp.getParentFile().exists()) { + if(tmp.getParentFile().getParentFile().exists()) { + File subBook = new File(tmp.getParentFile().getParentFile(), "book"); + return subBook; + //bookPath = new File(subBook, "varied.bin").getPath(); + //return bookPath; + } + } + } + return null; + } + + String getBookPath() { + File baseBook = getBaseBookPath(); + if(baseBook != null) { + String bookPath = new File(baseBook, "varied.bin").getPath(); + return bookPath; + } + return null; + } + + String getExtBookPath() { + + return "C:\\Users\\user\\MyFiles\\workspace\\extbook\\extbook.bin"; + + /* + File baseBook = getBaseBookPath(); + if(baseBook != null) { + String bookPath = new File(baseBook, "extbook.bin").getPath(); + return bookPath; + } + return null; +*/ + } + + String getStockfishPath() { + + String os = System.getProperty("os.name").toLowerCase(); + //System.out.println(os); + if(os.contains("win")) { + + String stockfishPath = ""; + String jarPath = ""; + String path = App.class.getProtectionDomain().getCodeSource().getLocation().getPath(); + jarPath = URLDecoder.decode(path, StandardCharsets.UTF_8); + File tmp = (new File(jarPath)); + if(tmp.getParentFile().exists()) { + File subEngine = new File(tmp.getParentFile(), "engine"); + stockfishPath = new File(subEngine, "stockfish_14.1.exe").getPath(); + return stockfishPath; + } + } + if(os.contains("linux")) { + String stockfishPath = ""; + String jarPath = ""; + String path = App.class.getProtectionDomain().getCodeSource().getLocation().getPath(); + //System.out.println(path); + jarPath = URLDecoder.decode(path, StandardCharsets.UTF_8); + //System.out.println(jarPath); + File tmp = (new File(jarPath)); + if(tmp.getParentFile().exists()) { + //System.out.println(tmp.getParentFile().getAbsolutePath()); + if(tmp.getParentFile().getParentFile().exists()) { + File subEngine = new File(tmp.getParentFile().getParentFile(), "engine"); + //System.out.println(subEngine.getPath()); + stockfishPath = new File(subEngine, "stockfish_x64").getPath(); + return stockfishPath; + } + } + + } + return null; + } +} From c5b324619528aadeea2b3b9c6f41aa51daf693f7 Mon Sep 17 00:00:00 2001 From: Manali Shah Date: Mon, 11 Apr 2022 23:14:41 -0300 Subject: [PATCH 3/4] Implementing Singleton and Prototype design pattern --- .../java/org/asdfjkl/jerryfx/gui/Chessboard.java | 2 +- .../asdfjkl/jerryfx/gui/DialogEnterPosition.java | 9 ++++++++- .../org/asdfjkl/jerryfx/gui/DialogPromotion.java | 2 +- .../org/asdfjkl/jerryfx/gui/EnterPosBoard.java | 2 +- .../asdfjkl/jerryfx/gui/PieceImageProvider.java | 10 ++++++++++ .../asdfjkl/jerryfx/gui/ShowAppearanceBoard.java | 2 +- src/main/java/org/asdfjkl/jerryfx/lib/Board.java | 14 ++++++++++++-- 7 files changed, 34 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/Chessboard.java b/src/main/java/org/asdfjkl/jerryfx/gui/Chessboard.java index 7572d74c..3aded3e1 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/Chessboard.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/Chessboard.java @@ -63,7 +63,7 @@ public Chessboard(GameModel gameModel) { boardStyle = new BoardStyle(); this.gameModel = gameModel; - pieceImageProvider = new PieceImageProvider(); + pieceImageProvider = PieceImageProvider.getInstance(); outputScaleX = Screen.getPrimary().getOutputScaleX(); grabbedPiece.setPiece(-1); moveSource = new Point(-1,-1); diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/DialogEnterPosition.java b/src/main/java/org/asdfjkl/jerryfx/gui/DialogEnterPosition.java index 7c61985d..9f696b0e 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/DialogEnterPosition.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/DialogEnterPosition.java @@ -42,7 +42,14 @@ public class DialogEnterPosition implements EnterPosBoardListener { EnterPosBoard enterPosBoard; - final Label lblCastlingRights = new Label("Castling Rights"); + //final Label lblCastlingRights = new Label("Castling Rights"); + Label lblCastlingRights; + Label getLblCastlingRightsInstance() { + if(lblCastlingRights==null) { + lblCastlingRights = new Label("Castling Rights"); + } + return lblCastlingRights; + } final CheckBox cbCastlesWK = new CheckBox("White O-O"); final CheckBox cbCastlesWQ = new CheckBox("White O-O-O"); final CheckBox cbCastlesBK = new CheckBox("Black O-O"); diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/DialogPromotion.java b/src/main/java/org/asdfjkl/jerryfx/gui/DialogPromotion.java index 614821cf..17d5c6be 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/DialogPromotion.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/DialogPromotion.java @@ -38,7 +38,7 @@ public class DialogPromotion { public static int show(boolean playerColor, int pieceStyle, int colorTheme) { - PieceImageProvider provider = new PieceImageProvider(); + PieceImageProvider provider = PieceImageProvider.getInstance(); choice = CONSTANTS.EMPTY; diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/EnterPosBoard.java b/src/main/java/org/asdfjkl/jerryfx/gui/EnterPosBoard.java index c8e10379..8cdf9c0f 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/EnterPosBoard.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/EnterPosBoard.java @@ -72,7 +72,7 @@ public EnterPosBoard(Board board) { this.boardStyle = new BoardStyle(); this.board = board; - this.pieceImageProvider = new PieceImageProvider(); + this.pieceImageProvider = PieceImageProvider.getInstance(); this.outputScaleX = Screen.getPrimary().getOutputScaleX(); this.grabbedPiece.setPiece(-1); diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/PieceImageProvider.java b/src/main/java/org/asdfjkl/jerryfx/gui/PieceImageProvider.java index 0b23ab4f..5609ec0c 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/PieceImageProvider.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/PieceImageProvider.java @@ -34,6 +34,16 @@ public class PieceImageProvider { + private static PieceImageProvider pieceImageProvider = null; + + private PieceImageProvider() {} + public static PieceImageProvider getInstance() { + if(pieceImageProvider == null) { + pieceImageProvider = new PieceImageProvider(); + } + return pieceImageProvider; + } + final HashMap whitePawnsMerida = new HashMap<>(); final HashMap blackPawnsMerida = new HashMap<>(); diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/ShowAppearanceBoard.java b/src/main/java/org/asdfjkl/jerryfx/gui/ShowAppearanceBoard.java index 80dd1b8a..16a192a7 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/ShowAppearanceBoard.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/ShowAppearanceBoard.java @@ -49,7 +49,7 @@ public class ShowAppearanceBoard extends CanvasProperties { public ShowAppearanceBoard() { this.boardStyle = new BoardStyle(); - this.pieceImageProvider = new PieceImageProvider(); + this.pieceImageProvider = PieceImageProvider.getInstance(); this.outputScaleX = Screen.getPrimary().getOutputScaleX(); this.board = new Board(true); diff --git a/src/main/java/org/asdfjkl/jerryfx/lib/Board.java b/src/main/java/org/asdfjkl/jerryfx/lib/Board.java index 4cdd3226..daf82ef3 100644 --- a/src/main/java/org/asdfjkl/jerryfx/lib/Board.java +++ b/src/main/java/org/asdfjkl/jerryfx/lib/Board.java @@ -23,7 +23,7 @@ import java.lang.Math; -public class Board { +public class Board implements Cloneable { public boolean turn; public int halfmoveClock; @@ -381,6 +381,16 @@ public void resetToStartingPosition() { } public Board makeCopy() { + Board cloneBoard = null; + try { + cloneBoard = (Board) this.clone(); + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + } + return cloneBoard; + } + + /* public Board makeCopy() { Board b = new Board(); @@ -425,7 +435,7 @@ public Board makeCopy() { return b; - } + }*/ public String fen() { String fenString = ""; From 3f9e4cfc892db50eeb76044c79fc382132a7f64c Mon Sep 17 00:00:00 2001 From: Manali Shah Date: Mon, 11 Apr 2022 23:20:03 -0300 Subject: [PATCH 4/4] removing unecessary --- .../org/asdfjkl/jerryfx/gui/DialogEnterPosition.java | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/main/java/org/asdfjkl/jerryfx/gui/DialogEnterPosition.java b/src/main/java/org/asdfjkl/jerryfx/gui/DialogEnterPosition.java index 9f696b0e..7c61985d 100644 --- a/src/main/java/org/asdfjkl/jerryfx/gui/DialogEnterPosition.java +++ b/src/main/java/org/asdfjkl/jerryfx/gui/DialogEnterPosition.java @@ -42,14 +42,7 @@ public class DialogEnterPosition implements EnterPosBoardListener { EnterPosBoard enterPosBoard; - //final Label lblCastlingRights = new Label("Castling Rights"); - Label lblCastlingRights; - Label getLblCastlingRightsInstance() { - if(lblCastlingRights==null) { - lblCastlingRights = new Label("Castling Rights"); - } - return lblCastlingRights; - } + final Label lblCastlingRights = new Label("Castling Rights"); final CheckBox cbCastlesWK = new CheckBox("White O-O"); final CheckBox cbCastlesWQ = new CheckBox("White O-O-O"); final CheckBox cbCastlesBK = new CheckBox("Black O-O");