From 7d27a33978084b733b7c9a72a29b67eaacce9281 Mon Sep 17 00:00:00 2001 From: junseoplee Date: Sat, 20 Jul 2024 02:29:09 +0900 Subject: [PATCH 01/23] =?UTF-8?q?fix:=20=ED=96=A5=EC=83=81=EB=90=9C=20?= =?UTF-8?q?=EB=AC=B8=EB=B2=95=EC=9C=BC=EB=A1=9C=20equals=20=EC=88=98?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/model/piece/Piece.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/chess/model/piece/Piece.java b/src/main/java/chess/model/piece/Piece.java index 2bf9e807b5..b84d8ef7ad 100644 --- a/src/main/java/chess/model/piece/Piece.java +++ b/src/main/java/chess/model/piece/Piece.java @@ -43,10 +43,13 @@ public void validateTurn(Color turn) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Piece piece = (Piece) o; - return color == piece.color && this.getClass().equals(piece.getClass()); + if (this == o) { + return true; + } + if (!(o instanceof Piece piece)) { + return false; + } + return color == piece.color; } @Override From d6ca9b589c2a7521b8d00282e044eb483cc72ec4 Mon Sep 17 00:00:00 2001 From: junseoplee Date: Sat, 20 Jul 2024 23:04:07 +0900 Subject: [PATCH 02/23] =?UTF-8?q?docs:=20=EA=B8=B0=EB=8A=A5=20=EC=9A=94?= =?UTF-8?q?=EA=B5=AC=20=EC=82=AC=ED=95=AD=20=EC=97=85=EB=8D=B0=EC=9D=B4?= =?UTF-8?q?=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index 1925cd54b6..348a29ae13 100644 --- a/README.md +++ b/README.md @@ -43,3 +43,17 @@ - [x] status 명령어를 입력하면 점수를 출력 - [x] 점수를 계산하는 ScoreCalculator 클래스 - [x] 같은 File 에 있는 Pawn 은 0.5점을 준다 + +## 4단계 - DB 적용 +### 기능 요구 사항 +- **DB 연결 전 기능** +- [ ] end 명령어를 입력하면 각자의 점수와 승리 팀을 출력한다 + - [ ] 점수를 계산해서 점수가 높은 팀이 승리한다 +- **DAO** +- [ ] 이전에 하던 체스 게임을 다시 시작할 수 있어야 한다 + - [ ] 사용자 ID로 사용자 엔티티를 조회한다 + - [ ] 사용자 ID를 저장한다 (이름은 10자 미만) + - [ ] 사용자 ID로 체스 게임을 조회한다 + - [ ] 사용자가 현재 진행 중인 체스 게임(체스판)을 저장한다 + - [ ] 진행 중이던 게임을 이어서 시작할 수 있다 + - [ ] 새로운 게임을 시작할 수 있다 From 5e9f8729cdcf13e1dc390a28ae0082625a5ca349 Mon Sep 17 00:00:00 2001 From: junseoplee Date: Sun, 21 Jul 2024 01:13:11 +0900 Subject: [PATCH 03/23] =?UTF-8?q?feat:=20=EC=8A=B9=EB=A6=AC=ED=95=9C=20?= =?UTF-8?q?=ED=8C=80=EC=9D=84=20=EC=B0=BE=EA=B3=A0=20=EC=B6=9C=EB=A0=A5?= =?UTF-8?q?=ED=95=98=EB=8A=94=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++-- .../chess/controller/ChessController.java | 22 ++++++++++++++++--- .../model/command/commands/EndCommand.java | 1 + src/main/java/chess/model/position/Color.java | 4 ++-- src/main/java/chess/view/OutputView.java | 14 +++++++++++- 5 files changed, 37 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 348a29ae13..322370df27 100644 --- a/README.md +++ b/README.md @@ -47,8 +47,8 @@ ## 4단계 - DB 적용 ### 기능 요구 사항 - **DB 연결 전 기능** -- [ ] end 명령어를 입력하면 각자의 점수와 승리 팀을 출력한다 - - [ ] 점수를 계산해서 점수가 높은 팀이 승리한다 +- [x] end 명령어를 입력하면 각자의 점수와 승리 팀을 출력한다 + - [x] 점수를 계산해서 점수가 높은 팀이 승리한다 - **DAO** - [ ] 이전에 하던 체스 게임을 다시 시작할 수 있어야 한다 - [ ] 사용자 ID로 사용자 엔티티를 조회한다 diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index a6fa065f02..21c4a508f1 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -57,10 +57,10 @@ public void runChess() { receivedCommand = commandFactory.createCommand(commandInput); if (receivedCommand.validateStatusCommandType()) { calculateAndPrintCurrentTurnScore(); - } else { - receivedCommand.execute(this); - currentTurn = currentTurn.changeTurn(currentTurn); + continue; } + receivedCommand.execute(this); + currentTurn = currentTurn.changeTurn(); } catch (IllegalArgumentException exception) { System.out.println(exception.getMessage()); } @@ -87,4 +87,20 @@ public void calculateAndPrintCurrentTurnScore() { double score = ScoreCalculator.calculate(board.getMap(), currentTurn); outputView.printCurrentTurnScore(currentTurn, score); } + + public void printScoreAndWinningColor() { + double currentTurnScore = ScoreCalculator.calculate(board.getMap(), currentTurn); + double opponentScore = ScoreCalculator.calculate(board.getMap(), currentTurn.changeTurn()); + outputView.printCurrentScore(currentTurn, currentTurnScore); + outputView.printCurrentScore(currentTurn.changeTurn(), opponentScore); + if (currentTurnScore > opponentScore) { + outputView.printWinningColor(currentTurn); + } + if (opponentScore > currentTurnScore) { + outputView.printWinningColor(currentTurn.changeTurn()); + } + if (currentTurnScore == opponentScore) { + outputView.printDraw(); + } + } } diff --git a/src/main/java/chess/model/command/commands/EndCommand.java b/src/main/java/chess/model/command/commands/EndCommand.java index a64a657b26..0ef02c1870 100644 --- a/src/main/java/chess/model/command/commands/EndCommand.java +++ b/src/main/java/chess/model/command/commands/EndCommand.java @@ -6,6 +6,7 @@ public class EndCommand implements CommandLauncher { @Override public void execute(ChessController controller) { + controller.printScoreAndWinningColor(); controller.endGame(); } diff --git a/src/main/java/chess/model/position/Color.java b/src/main/java/chess/model/position/Color.java index 331da6b40c..c3171b681f 100644 --- a/src/main/java/chess/model/position/Color.java +++ b/src/main/java/chess/model/position/Color.java @@ -9,8 +9,8 @@ public boolean isSameColor(Color color) { return this == color; } - public Color changeTurn(Color currentTurn) { - if (currentTurn == WHITE) { + public Color changeTurn() { + if (this == WHITE) { return BLACK; } return WHITE; diff --git a/src/main/java/chess/view/OutputView.java b/src/main/java/chess/view/OutputView.java index 0226556f59..c9ed823c60 100644 --- a/src/main/java/chess/view/OutputView.java +++ b/src/main/java/chess/view/OutputView.java @@ -21,7 +21,7 @@ public void printStartMessage() { System.out.println("> 체스 게임을 시작합니다."); System.out.println("> 게임 시작 : start"); System.out.println("> 게임 종료 : end"); - System.out.println("> 게임 이동 : move source위치 target위치 - 예. move b2 b3"); + System.out.println("> 게임 이동 : move source 위치 target 위치 - 예. move b2 b3"); } public void printBoard(final Map boardMap) { @@ -58,4 +58,16 @@ private List> createEmptyBoard() { .mapToObj(it -> new ArrayList<>(Collections.nCopies(BOARD_SIZE, Symbol.EMPTY.getSymbol()))) .collect(Collectors.toList()); } + + public void printCurrentScore(Color currentTurn, double score) { + System.out.println("Color: " + currentTurn + ", Score: " + score); + } + + public void printWinningColor(Color currentTurn) { + System.out.println("Winning Color: " + currentTurn); + } + + public void printDraw() { + System.out.println("Draw"); + } } From fba2d7315a829612f66d65c38df32be183062eda Mon Sep 17 00:00:00 2001 From: junseoplee Date: Mon, 22 Jul 2024 14:12:21 +0900 Subject: [PATCH 04/23] =?UTF-8?q?feat:=20King=20=EC=9D=B4=20=EC=9E=A1?= =?UTF-8?q?=ED=98=94=EC=9D=84=20=EB=95=8C=20=EC=8A=B9=EB=A6=AC=20=ED=8C=80?= =?UTF-8?q?=EA=B3=BC=20=EC=A0=90=EC=88=98=EB=A5=BC=20=EC=B6=9C=EB=A0=A5?= =?UTF-8?q?=ED=95=98=EB=8A=94=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/chess/controller/ChessController.java | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index 21c4a508f1..c988f1c4b3 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -56,8 +56,8 @@ public void runChess() { String commandInput = inputView.receiveCommand(); receivedCommand = commandFactory.createCommand(commandInput); if (receivedCommand.validateStatusCommandType()) { - calculateAndPrintCurrentTurnScore(); - continue; + receivedCommand.execute(this); + continue; // 명령이 status 일 경우 턴을 바꾸지 않음 } receivedCommand.execute(this); currentTurn = currentTurn.changeTurn(); @@ -77,9 +77,7 @@ public void endGame() { public void movePiece(Position source, Position target) { Piece capturedPiece = board.move(source, target, currentTurn); - if (capturedPiece != null && capturedPiece.pieceType() == PieceInfo.KING) { - endGame(); - } + checkAndHandleKingCapture(capturedPiece, currentTurn); outputView.printBoard(board.getMap()); } @@ -103,4 +101,13 @@ public void printScoreAndWinningColor() { outputView.printDraw(); } } + + private void checkAndHandleKingCapture(Piece capturedPiece, Color currentTurn) { + if (capturedPiece != null && capturedPiece.pieceType() == PieceInfo.KING) { + endGame(); + double currentTurnScore = ScoreCalculator.calculate(board.getMap(), currentTurn); + outputView.printCurrentScore(currentTurn, currentTurnScore); + outputView.printWinningColor(currentTurn); + } + } } From 90f634b29a0e04bdfbda3f94c107f2260481818d Mon Sep 17 00:00:00 2001 From: junseoplee Date: Tue, 23 Jul 2024 00:37:51 +0900 Subject: [PATCH 05/23] =?UTF-8?q?fix:=20Pawn=20=ED=94=BC=EC=8A=A4=EA=B0=80?= =?UTF-8?q?=20=EC=A0=81=EC=9D=B4=20=EC=97=86=EC=9D=84=20=EA=B2=BD=EC=9A=B0?= =?UTF-8?q?=EC=97=90=EB=8F=84=20=EB=8C=80=EA=B0=81=EC=84=A0=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EC=9B=80=EC=A7=81=EC=9D=BC=20=EC=88=98=20=EC=9E=88?= =?UTF-8?q?=EB=8D=98=20=EC=98=A4=EB=A5=98=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/model/board/Board.java | 2 +- src/main/java/chess/model/piece/Piece.java | 3 ++- .../java/chess/model/piece/pieces/Bishop.java | 3 ++- .../java/chess/model/piece/pieces/King.java | 3 ++- .../java/chess/model/piece/pieces/Knight.java | 3 ++- .../java/chess/model/piece/pieces/Pawn.java | 20 +++++++++++-------- .../java/chess/model/piece/pieces/Queen.java | 3 ++- .../java/chess/model/piece/pieces/Rook.java | 3 ++- 8 files changed, 25 insertions(+), 15 deletions(-) diff --git a/src/main/java/chess/model/board/Board.java b/src/main/java/chess/model/board/Board.java index dba3f4ac17..7368ee9217 100644 --- a/src/main/java/chess/model/board/Board.java +++ b/src/main/java/chess/model/board/Board.java @@ -47,7 +47,7 @@ private void validatePath(Position from, Position to) { Set positionsWithOutTarget = new HashSet<>(board.keySet()); positionsWithOutTarget.remove(to); - Path path = source.findPath(from, to); + Path path = source.findPath(from, to, board); path.validateObstacle(positionsWithOutTarget); } diff --git a/src/main/java/chess/model/piece/Piece.java b/src/main/java/chess/model/piece/Piece.java index b84d8ef7ad..f3c82b76b8 100644 --- a/src/main/java/chess/model/piece/Piece.java +++ b/src/main/java/chess/model/piece/Piece.java @@ -6,6 +6,7 @@ import chess.model.position.Position; import chess.model.ErrorMessage; import java.util.List; +import java.util.Map; import java.util.Objects; public abstract class Piece { @@ -16,7 +17,7 @@ public Piece(final Color color) { this.color = color; } - public abstract Path findPath(Position from, Position to); + public abstract Path findPath(Position from, Position to, Map board); public abstract PieceInfo pieceType(); diff --git a/src/main/java/chess/model/piece/pieces/Bishop.java b/src/main/java/chess/model/piece/pieces/Bishop.java index 5594f9c7dd..42be0071a5 100644 --- a/src/main/java/chess/model/piece/pieces/Bishop.java +++ b/src/main/java/chess/model/piece/pieces/Bishop.java @@ -10,6 +10,7 @@ import chess.model.position.Position; import java.util.ArrayList; import java.util.List; +import java.util.Map; public class Bishop extends Piece { @@ -21,7 +22,7 @@ public Bishop(final Color color) { } @Override - public Path findPath(Position from, Position to) { + public Path findPath(Position from, Position to, final Map board) { Movement movement = convertMovement(from, to); validateMovement(movement, availableMovements); diff --git a/src/main/java/chess/model/piece/pieces/King.java b/src/main/java/chess/model/piece/pieces/King.java index 63dfff1a2f..c15f429eb7 100644 --- a/src/main/java/chess/model/piece/pieces/King.java +++ b/src/main/java/chess/model/piece/pieces/King.java @@ -10,6 +10,7 @@ import chess.model.position.Position; import chess.model.ErrorMessage; import java.util.List; +import java.util.Map; public class King extends Piece { @@ -22,7 +23,7 @@ public King(final Color color) { } @Override - public Path findPath(Position from, Position to) { + public Path findPath(Position from, Position to, final Map board) { Movement movement = convertMovement(from, to); validateMovement(movement, availableMovements); diff --git a/src/main/java/chess/model/piece/pieces/Knight.java b/src/main/java/chess/model/piece/pieces/Knight.java index 433cbae3d4..c12e546b3e 100644 --- a/src/main/java/chess/model/piece/pieces/Knight.java +++ b/src/main/java/chess/model/piece/pieces/Knight.java @@ -11,6 +11,7 @@ import chess.model.ErrorMessage; import java.util.List; +import java.util.Map; public class Knight extends Piece { @@ -25,7 +26,7 @@ public Knight(final Color color) { } @Override - public Path findPath(Position from, Position to) { + public Path findPath(Position from, Position to, final Map board) { Movement movement = convertMovement(from, to); validateMovement(movement, availableMovements); diff --git a/src/main/java/chess/model/piece/pieces/Pawn.java b/src/main/java/chess/model/piece/pieces/Pawn.java index 153b48874a..febdcfed97 100644 --- a/src/main/java/chess/model/piece/pieces/Pawn.java +++ b/src/main/java/chess/model/piece/pieces/Pawn.java @@ -41,25 +41,29 @@ public Pawn(final Color color) { } @Override - public Path findPath(final Position from, final Position to) { + public Path findPath(final Position from, final Position to, final Map board) { Movement movement = convertMovement(from, to); - - if (isAttackMovement(movement)) { // 공격 움직임인 경우 - return findPathForAttackMovement(to, movement); + if (isAttackMovement(movement)) { + return findPathForAttackMovement(to, movement, board); } - - return findPathForEmptyPosition(from, to, movement); // 빈 칸으로 이동하는 경우 + return findPathForEmptyPosition(from, to, movement); } private boolean isAttackMovement(final Movement movement) { return AVAILABLE_ATTACK_MOVEMENTS.get(getColor()).contains(movement); } - private Path findPathForAttackMovement(final Position to, final Movement movement) { + private Path findPathForAttackMovement(final Position to, final Movement movement, final Map board) { validateMovement(movement, AVAILABLE_ATTACK_MOVEMENTS.get(getColor())); - + validateAttackMovement(to, board); return new Path(List.of(to)); } + private void validateAttackMovement(final Position to, final Map board) { + Piece targetPiece = board.get(to); + if (targetPiece == null || targetPiece.getColor() == this.getColor()) { + throw new IllegalArgumentException(ErrorMessage.INVALID_DIRECTION.getMessage()); + } + } private Path findPathForEmptyPosition(final Position from, final Position to, final Movement movement) { validateMovement(movement, List.of(AVAILABLE_MOVEMENTS.get(getColor()))); diff --git a/src/main/java/chess/model/piece/pieces/Queen.java b/src/main/java/chess/model/piece/pieces/Queen.java index cdc7b89275..4803ef0ea1 100644 --- a/src/main/java/chess/model/piece/pieces/Queen.java +++ b/src/main/java/chess/model/piece/pieces/Queen.java @@ -12,6 +12,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Map; public class Queen extends Piece { @@ -25,7 +26,7 @@ public Queen(final Color color) { } @Override - public Path findPath(final Position from, final Position to) { + public Path findPath(final Position from, final Position to, final Map board) { Movement movement = convertMovement(from, to); validateMovement(movement, availableMovements); diff --git a/src/main/java/chess/model/piece/pieces/Rook.java b/src/main/java/chess/model/piece/pieces/Rook.java index db9e086f43..732d57a0f2 100644 --- a/src/main/java/chess/model/piece/pieces/Rook.java +++ b/src/main/java/chess/model/piece/pieces/Rook.java @@ -12,6 +12,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Map; public class Rook extends Piece { @@ -24,7 +25,7 @@ public Rook(final Color color) { } @Override - public Path findPath(final Position from, final Position to) { + public Path findPath(final Position from, final Position to, final Map board) { Movement movement = convertMovement(from, to); validateMovement(movement, availableMovements); From 89edcb7afaf095f5b023a61b9b11b455095521d2 Mon Sep 17 00:00:00 2001 From: junseoplee Date: Tue, 23 Jul 2024 01:30:10 +0900 Subject: [PATCH 06/23] =?UTF-8?q?docs:=20=EA=B8=B0=EB=8A=A5=20=EC=9A=94?= =?UTF-8?q?=EA=B5=AC=20=EC=82=AC=ED=95=AD=20=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 44 ++++++++++++++++++++++++++++++++++---------- 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 322370df27..3ff85a5387 100644 --- a/README.md +++ b/README.md @@ -33,11 +33,11 @@ - [x] 체스 말이 반환한 경로 안에 다른 체스 말이 있는지 검사 - [x] 경로 안에 다른 체스 말이 있다면 이동할 수 없다 <- Path - **입력** -- [x] move source위치 target위치을 실행해 이동한다 +- [x] move source 위치 target 위치을 실행해 이동한다 ## 3단계 - 승패 및 점수 ### 기능 요구 사항 -- [x] King이 잡혔을 때 게임을 종료해야 한다 +- [x] King 이 잡혔을 때 게임을 종료해야 한다 - [x] 체스판에서 잡힌 말을 반환 - [x] 체스 말에서 해당 말의 타입을 반환 - [x] status 명령어를 입력하면 점수를 출력 @@ -49,11 +49,35 @@ - **DB 연결 전 기능** - [x] end 명령어를 입력하면 각자의 점수와 승리 팀을 출력한다 - [x] 점수를 계산해서 점수가 높은 팀이 승리한다 -- **DAO** -- [ ] 이전에 하던 체스 게임을 다시 시작할 수 있어야 한다 - - [ ] 사용자 ID로 사용자 엔티티를 조회한다 - - [ ] 사용자 ID를 저장한다 (이름은 10자 미만) - - [ ] 사용자 ID로 체스 게임을 조회한다 - - [ ] 사용자가 현재 진행 중인 체스 게임(체스판)을 저장한다 - - [ ] 진행 중이던 게임을 이어서 시작할 수 있다 - - [ ] 새로운 게임을 시작할 수 있다 +- **DB 연결** +- [ ] 애플리케이션을 재시작하더라도 이전에 하던 체스 게임을 다시 시작할 수 있어야 한다 + - [ ] 이어하기 + - 이전에 진행하던 게임이 있다면 이어서 게임을 시작한다 + - 이전에 진행하던 게임이 없다면 새로운 게임을 시작한다 + - [ ] 새로하기 + - 이전에 진행하던 게임이 있어도 새로운 게임을 시작한다 +- 현재 턴을 따로 저장해야한다 -> ChessController 리팩토링 +- [ ] 피스를 이동할 때 마다 피스 테이블을 업데이트한다 +- [ ] 체스 게임을 저장할 수 있다 -> ChessDao +- [ ] 체스 게임을 찾을 수 있다 +- [ ] 체스 게임을 삭제할 수 있다 + +``` +CREATE TABLE chess_games ( + id BIGINT NOT NULL AUTO_INCREMENT, + current_turn VARCHAR(16) NOT NULL, + PRIMARY KEY (id) +); + +CREATE TABLE pieces ( + id BIGINT NOT NULL AUTO_INCREMENT, + game_id BIGINT NOT NULL, + piece_file INT NOT NULL, + piece_rank INT NOT NULL, + color VARCHAR(16) NOT NULL, + type VARCHAR(16) NOT NULL, + PRIMARY KEY (id), + FOREIGN KEY (game_id) REFERENCES games(id) +); + +``` From 0218cecc5e6ee2074e8cd5b51ed9362d3a148c5e Mon Sep 17 00:00:00 2001 From: junseoplee Date: Tue, 23 Jul 2024 18:08:52 +0900 Subject: [PATCH 07/23] =?UTF-8?q?refactor:=20=ED=94=84=EB=A1=9C=EC=A0=9D?= =?UTF-8?q?=ED=8A=B8=20=EA=B5=AC=EC=A1=B0=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chess/{model => domain}/board/Board.java | 14 ++++++------ .../{model => domain}/board/InitialBoard.java | 22 +++++++++---------- .../command/CommandFactory.java | 16 +++++++------- .../command/CommandLauncher.java | 2 +- .../command/commands/EndCommand.java | 5 +++-- .../command/commands/MoveCommand.java | 7 +++--- .../command/commands/StartCommand.java | 5 +++-- .../command/commands/StatusCommand.java | 5 +++-- .../game}/ScoreCalculator.java | 10 ++++----- .../{model => domain}/movement/Movement.java | 4 ++-- .../movement/MovementConverter.java | 7 +++--- .../{model => domain}/movement/Path.java | 6 ++--- .../chess/{model => domain}/piece/Piece.java | 12 +++++----- .../{model => domain}/piece/PieceInfo.java | 2 +- .../piece/pieces/Bishop.java | 16 +++++++------- .../{model => domain}/piece/pieces/King.java | 18 +++++++-------- .../piece/pieces/Knight.java | 18 +++++++-------- .../{model => domain}/piece/pieces/Pawn.java | 20 ++++++++--------- .../{model => domain}/piece/pieces/Queen.java | 16 +++++++------- .../{model => domain}/piece/pieces/Rook.java | 16 +++++++------- .../{model => domain}/position/Color.java | 3 +-- .../{model => domain}/position/File.java | 4 ++-- .../position/InitialPosition.java | 2 +- .../{model => domain}/position/Position.java | 5 +++-- .../{model => domain}/position/Rank.java | 4 ++-- 25 files changed, 122 insertions(+), 117 deletions(-) rename src/main/java/chess/{model => domain}/board/Board.java (81%) rename src/main/java/chess/{model => domain}/board/InitialBoard.java (87%) rename src/main/java/chess/{model => domain}/command/CommandFactory.java (86%) rename src/main/java/chess/{model => domain}/command/CommandLauncher.java (87%) rename src/main/java/chess/{model => domain}/command/commands/EndCommand.java (82%) rename src/main/java/chess/{model => domain}/command/commands/MoveCommand.java (81%) rename src/main/java/chess/{model => domain}/command/commands/StartCommand.java (80%) rename src/main/java/chess/{model => domain}/command/commands/StatusCommand.java (81%) rename src/main/java/chess/{model/score => domain/game}/ScoreCalculator.java (87%) rename src/main/java/chess/{model => domain}/movement/Movement.java (94%) rename src/main/java/chess/{model => domain}/movement/MovementConverter.java (87%) rename src/main/java/chess/{model => domain}/movement/Path.java (83%) rename src/main/java/chess/{model => domain}/piece/Piece.java (86%) rename src/main/java/chess/{model => domain}/piece/PieceInfo.java (90%) rename src/main/java/chess/{model => domain}/piece/pieces/Bishop.java (76%) rename src/main/java/chess/{model => domain}/piece/pieces/King.java (74%) rename src/main/java/chess/{model => domain}/piece/pieces/Knight.java (75%) rename src/main/java/chess/{model => domain}/piece/pieces/Pawn.java (88%) rename src/main/java/chess/{model => domain}/piece/pieces/Queen.java (77%) rename src/main/java/chess/{model => domain}/piece/pieces/Rook.java (75%) rename src/main/java/chess/{model => domain}/position/Color.java (87%) rename src/main/java/chess/{model => domain}/position/File.java (90%) rename src/main/java/chess/{model => domain}/position/InitialPosition.java (97%) rename src/main/java/chess/{model => domain}/position/Position.java (93%) rename src/main/java/chess/{model => domain}/position/Rank.java (90%) diff --git a/src/main/java/chess/model/board/Board.java b/src/main/java/chess/domain/board/Board.java similarity index 81% rename from src/main/java/chess/model/board/Board.java rename to src/main/java/chess/domain/board/Board.java index 7368ee9217..59773c6fcd 100644 --- a/src/main/java/chess/model/board/Board.java +++ b/src/main/java/chess/domain/board/Board.java @@ -1,10 +1,10 @@ -package chess.model.board; +package chess.domain.board; -import chess.model.movement.Path; -import chess.model.piece.Piece; -import chess.model.position.Color; -import chess.model.position.Position; -import chess.model.ErrorMessage; +import chess.domain.movement.Path; +import chess.domain.piece.Piece; +import chess.domain.position.Color; +import chess.domain.position.Position; +import chess.domain.ErrorMessage; import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -17,7 +17,7 @@ public Board(final Map board) { this.board = board; } - public Piece move(final Position from, final Position to, final Color turn) { + public Piece moveAndReturnPiece(final Position from, final Position to, final Color turn) { validateMove(from, to, turn); Piece piece = board.remove(from); return board.put(to, piece); diff --git a/src/main/java/chess/model/board/InitialBoard.java b/src/main/java/chess/domain/board/InitialBoard.java similarity index 87% rename from src/main/java/chess/model/board/InitialBoard.java rename to src/main/java/chess/domain/board/InitialBoard.java index a9052e9f24..4e35544640 100644 --- a/src/main/java/chess/model/board/InitialBoard.java +++ b/src/main/java/chess/domain/board/InitialBoard.java @@ -1,15 +1,15 @@ -package chess.model.board; +package chess.domain.board; -import chess.model.piece.Piece; -import chess.model.piece.pieces.Bishop; -import chess.model.piece.pieces.King; -import chess.model.piece.pieces.Knight; -import chess.model.piece.pieces.Pawn; -import chess.model.piece.pieces.Queen; -import chess.model.piece.pieces.Rook; -import chess.model.position.Color; -import chess.model.position.Position; -import chess.model.position.InitialPosition; +import chess.domain.piece.Piece; +import chess.domain.piece.pieces.Bishop; +import chess.domain.piece.pieces.King; +import chess.domain.piece.pieces.Knight; +import chess.domain.piece.pieces.Pawn; +import chess.domain.piece.pieces.Queen; +import chess.domain.piece.pieces.Rook; +import chess.domain.position.Color; +import chess.domain.position.Position; +import chess.domain.position.InitialPosition; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/chess/model/command/CommandFactory.java b/src/main/java/chess/domain/command/CommandFactory.java similarity index 86% rename from src/main/java/chess/model/command/CommandFactory.java rename to src/main/java/chess/domain/command/CommandFactory.java index f33fc03b5a..1afde2ae15 100644 --- a/src/main/java/chess/model/command/CommandFactory.java +++ b/src/main/java/chess/domain/command/CommandFactory.java @@ -1,11 +1,11 @@ -package chess.model.command; - -import chess.model.command.commands.EndCommand; -import chess.model.command.commands.MoveCommand; -import chess.model.command.commands.StartCommand; -import chess.model.ErrorMessage; -import chess.model.command.commands.StatusCommand; -import chess.model.position.Position; +package chess.domain.command; + +import chess.domain.command.commands.EndCommand; +import chess.domain.command.commands.MoveCommand; +import chess.domain.command.commands.StartCommand; +import chess.domain.ErrorMessage; +import chess.domain.command.commands.StatusCommand; +import chess.domain.position.Position; import java.util.HashMap; import java.util.List; import java.util.Map; diff --git a/src/main/java/chess/model/command/CommandLauncher.java b/src/main/java/chess/domain/command/CommandLauncher.java similarity index 87% rename from src/main/java/chess/model/command/CommandLauncher.java rename to src/main/java/chess/domain/command/CommandLauncher.java index 986e46aa09..bff74b588e 100644 --- a/src/main/java/chess/model/command/CommandLauncher.java +++ b/src/main/java/chess/domain/command/CommandLauncher.java @@ -1,4 +1,4 @@ -package chess.model.command; +package chess.domain.command; import chess.controller.ChessController; diff --git a/src/main/java/chess/model/command/commands/EndCommand.java b/src/main/java/chess/domain/command/commands/EndCommand.java similarity index 82% rename from src/main/java/chess/model/command/commands/EndCommand.java rename to src/main/java/chess/domain/command/commands/EndCommand.java index 0ef02c1870..3cbfe99ec4 100644 --- a/src/main/java/chess/model/command/commands/EndCommand.java +++ b/src/main/java/chess/domain/command/commands/EndCommand.java @@ -1,9 +1,10 @@ -package chess.model.command.commands; +package chess.domain.command.commands; import chess.controller.ChessController; -import chess.model.command.CommandLauncher; +import chess.domain.command.CommandLauncher; public class EndCommand implements CommandLauncher { + @Override public void execute(ChessController controller) { controller.printScoreAndWinningColor(); diff --git a/src/main/java/chess/model/command/commands/MoveCommand.java b/src/main/java/chess/domain/command/commands/MoveCommand.java similarity index 81% rename from src/main/java/chess/model/command/commands/MoveCommand.java rename to src/main/java/chess/domain/command/commands/MoveCommand.java index 40eeafca1c..c48538e22e 100644 --- a/src/main/java/chess/model/command/commands/MoveCommand.java +++ b/src/main/java/chess/domain/command/commands/MoveCommand.java @@ -1,10 +1,11 @@ -package chess.model.command.commands; +package chess.domain.command.commands; import chess.controller.ChessController; -import chess.model.command.CommandLauncher; -import chess.model.position.Position; +import chess.domain.command.CommandLauncher; +import chess.domain.position.Position; public class MoveCommand implements CommandLauncher { + private final Position source; private final Position target; diff --git a/src/main/java/chess/model/command/commands/StartCommand.java b/src/main/java/chess/domain/command/commands/StartCommand.java similarity index 80% rename from src/main/java/chess/model/command/commands/StartCommand.java rename to src/main/java/chess/domain/command/commands/StartCommand.java index 7361d88244..65434f84eb 100644 --- a/src/main/java/chess/model/command/commands/StartCommand.java +++ b/src/main/java/chess/domain/command/commands/StartCommand.java @@ -1,9 +1,10 @@ -package chess.model.command.commands; +package chess.domain.command.commands; import chess.controller.ChessController; -import chess.model.command.CommandLauncher; +import chess.domain.command.CommandLauncher; public class StartCommand implements CommandLauncher { + @Override public void execute(ChessController controller) { controller.startGame(); diff --git a/src/main/java/chess/model/command/commands/StatusCommand.java b/src/main/java/chess/domain/command/commands/StatusCommand.java similarity index 81% rename from src/main/java/chess/model/command/commands/StatusCommand.java rename to src/main/java/chess/domain/command/commands/StatusCommand.java index a995bce054..9bd7ecd360 100644 --- a/src/main/java/chess/model/command/commands/StatusCommand.java +++ b/src/main/java/chess/domain/command/commands/StatusCommand.java @@ -1,9 +1,10 @@ -package chess.model.command.commands; +package chess.domain.command.commands; import chess.controller.ChessController; -import chess.model.command.CommandLauncher; +import chess.domain.command.CommandLauncher; public class StatusCommand implements CommandLauncher { + @Override public void execute(ChessController controller) { controller.calculateAndPrintCurrentTurnScore(); diff --git a/src/main/java/chess/model/score/ScoreCalculator.java b/src/main/java/chess/domain/game/ScoreCalculator.java similarity index 87% rename from src/main/java/chess/model/score/ScoreCalculator.java rename to src/main/java/chess/domain/game/ScoreCalculator.java index 38d2462f53..ea8144358b 100644 --- a/src/main/java/chess/model/score/ScoreCalculator.java +++ b/src/main/java/chess/domain/game/ScoreCalculator.java @@ -1,9 +1,9 @@ -package chess.model.score; +package chess.domain.game; -import chess.model.piece.Piece; -import chess.model.piece.PieceInfo; -import chess.model.position.Color; -import chess.model.position.Position; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceInfo; +import chess.domain.position.Color; +import chess.domain.position.Position; import java.util.List; import java.util.Map; diff --git a/src/main/java/chess/model/movement/Movement.java b/src/main/java/chess/domain/movement/Movement.java similarity index 94% rename from src/main/java/chess/model/movement/Movement.java rename to src/main/java/chess/domain/movement/Movement.java index c35ab9262f..e4072f5450 100644 --- a/src/main/java/chess/model/movement/Movement.java +++ b/src/main/java/chess/domain/movement/Movement.java @@ -1,6 +1,6 @@ -package chess.model.movement; +package chess.domain.movement; -import chess.model.ErrorMessage; +import chess.domain.ErrorMessage; import java.util.Arrays; public enum Movement { diff --git a/src/main/java/chess/model/movement/MovementConverter.java b/src/main/java/chess/domain/movement/MovementConverter.java similarity index 87% rename from src/main/java/chess/model/movement/MovementConverter.java rename to src/main/java/chess/domain/movement/MovementConverter.java index 7944c55aa4..46a12bbea7 100644 --- a/src/main/java/chess/model/movement/MovementConverter.java +++ b/src/main/java/chess/domain/movement/MovementConverter.java @@ -1,10 +1,11 @@ -package chess.model.movement; +package chess.domain.movement; -import chess.model.position.Position; -import chess.model.ErrorMessage; +import chess.domain.position.Position; +import chess.domain.ErrorMessage; import java.math.BigInteger; public class MovementConverter { + public static Movement convertMovement(Position from, Position to) { int fileDiff = to.calculateFileDiff(from); int rankDiff = to.calculateRankDiff(from); diff --git a/src/main/java/chess/model/movement/Path.java b/src/main/java/chess/domain/movement/Path.java similarity index 83% rename from src/main/java/chess/model/movement/Path.java rename to src/main/java/chess/domain/movement/Path.java index b603a2ecbb..0615d0418b 100644 --- a/src/main/java/chess/model/movement/Path.java +++ b/src/main/java/chess/domain/movement/Path.java @@ -1,7 +1,7 @@ -package chess.model.movement; +package chess.domain.movement; -import chess.model.position.Position; -import chess.model.ErrorMessage; +import chess.domain.position.Position; +import chess.domain.ErrorMessage; import java.util.ArrayList; import java.util.List; import java.util.Set; diff --git a/src/main/java/chess/model/piece/Piece.java b/src/main/java/chess/domain/piece/Piece.java similarity index 86% rename from src/main/java/chess/model/piece/Piece.java rename to src/main/java/chess/domain/piece/Piece.java index f3c82b76b8..acda0baede 100644 --- a/src/main/java/chess/model/piece/Piece.java +++ b/src/main/java/chess/domain/piece/Piece.java @@ -1,10 +1,10 @@ -package chess.model.piece; +package chess.domain.piece; -import chess.model.movement.Movement; -import chess.model.movement.Path; -import chess.model.position.Color; -import chess.model.position.Position; -import chess.model.ErrorMessage; +import chess.domain.movement.Movement; +import chess.domain.movement.Path; +import chess.domain.position.Color; +import chess.domain.position.Position; +import chess.domain.ErrorMessage; import java.util.List; import java.util.Map; import java.util.Objects; diff --git a/src/main/java/chess/model/piece/PieceInfo.java b/src/main/java/chess/domain/piece/PieceInfo.java similarity index 90% rename from src/main/java/chess/model/piece/PieceInfo.java rename to src/main/java/chess/domain/piece/PieceInfo.java index c981a90f88..9d5e62edfb 100644 --- a/src/main/java/chess/model/piece/PieceInfo.java +++ b/src/main/java/chess/domain/piece/PieceInfo.java @@ -1,4 +1,4 @@ -package chess.model.piece; +package chess.domain.piece; public enum PieceInfo { KING(0), diff --git a/src/main/java/chess/model/piece/pieces/Bishop.java b/src/main/java/chess/domain/piece/pieces/Bishop.java similarity index 76% rename from src/main/java/chess/model/piece/pieces/Bishop.java rename to src/main/java/chess/domain/piece/pieces/Bishop.java index 42be0071a5..7a1790889c 100644 --- a/src/main/java/chess/model/piece/pieces/Bishop.java +++ b/src/main/java/chess/domain/piece/pieces/Bishop.java @@ -1,13 +1,13 @@ -package chess.model.piece.pieces; +package chess.domain.piece.pieces; -import static chess.model.movement.MovementConverter.convertMovement; +import static chess.domain.movement.MovementConverter.convertMovement; -import chess.model.movement.Movement; -import chess.model.movement.Path; -import chess.model.piece.Piece; -import chess.model.piece.PieceInfo; -import chess.model.position.Color; -import chess.model.position.Position; +import chess.domain.movement.Movement; +import chess.domain.movement.Path; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceInfo; +import chess.domain.position.Color; +import chess.domain.position.Position; import java.util.ArrayList; import java.util.List; import java.util.Map; diff --git a/src/main/java/chess/model/piece/pieces/King.java b/src/main/java/chess/domain/piece/pieces/King.java similarity index 74% rename from src/main/java/chess/model/piece/pieces/King.java rename to src/main/java/chess/domain/piece/pieces/King.java index c15f429eb7..4fcd2bf7a9 100644 --- a/src/main/java/chess/model/piece/pieces/King.java +++ b/src/main/java/chess/domain/piece/pieces/King.java @@ -1,14 +1,14 @@ -package chess.model.piece.pieces; +package chess.domain.piece.pieces; -import static chess.model.movement.MovementConverter.convertMovement; +import static chess.domain.movement.MovementConverter.convertMovement; -import chess.model.movement.Movement; -import chess.model.movement.Path; -import chess.model.piece.Piece; -import chess.model.piece.PieceInfo; -import chess.model.position.Color; -import chess.model.position.Position; -import chess.model.ErrorMessage; +import chess.domain.movement.Movement; +import chess.domain.movement.Path; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceInfo; +import chess.domain.position.Color; +import chess.domain.position.Position; +import chess.domain.ErrorMessage; import java.util.List; import java.util.Map; diff --git a/src/main/java/chess/model/piece/pieces/Knight.java b/src/main/java/chess/domain/piece/pieces/Knight.java similarity index 75% rename from src/main/java/chess/model/piece/pieces/Knight.java rename to src/main/java/chess/domain/piece/pieces/Knight.java index c12e546b3e..ff0a51fc78 100644 --- a/src/main/java/chess/model/piece/pieces/Knight.java +++ b/src/main/java/chess/domain/piece/pieces/Knight.java @@ -1,14 +1,14 @@ -package chess.model.piece.pieces; +package chess.domain.piece.pieces; -import static chess.model.movement.MovementConverter.convertMovement; +import static chess.domain.movement.MovementConverter.convertMovement; -import chess.model.movement.Movement; -import chess.model.movement.Path; -import chess.model.piece.Piece; -import chess.model.piece.PieceInfo; -import chess.model.position.Color; -import chess.model.position.Position; -import chess.model.ErrorMessage; +import chess.domain.movement.Movement; +import chess.domain.movement.Path; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceInfo; +import chess.domain.position.Color; +import chess.domain.position.Position; +import chess.domain.ErrorMessage; import java.util.List; import java.util.Map; diff --git a/src/main/java/chess/model/piece/pieces/Pawn.java b/src/main/java/chess/domain/piece/pieces/Pawn.java similarity index 88% rename from src/main/java/chess/model/piece/pieces/Pawn.java rename to src/main/java/chess/domain/piece/pieces/Pawn.java index febdcfed97..e5cc5f1b47 100644 --- a/src/main/java/chess/model/piece/pieces/Pawn.java +++ b/src/main/java/chess/domain/piece/pieces/Pawn.java @@ -1,18 +1,18 @@ -package chess.model.piece.pieces; +package chess.domain.piece.pieces; -import chess.model.movement.Movement; -import chess.model.movement.Path; -import chess.model.piece.Piece; -import chess.model.piece.PieceInfo; -import chess.model.position.Color; -import chess.model.position.Position; +import chess.domain.movement.Movement; +import chess.domain.movement.Path; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceInfo; +import chess.domain.position.Color; +import chess.domain.position.Position; -import chess.model.ErrorMessage; +import chess.domain.ErrorMessage; import java.util.List; import java.util.Map; -import static chess.model.movement.Movement.*; -import static chess.model.movement.MovementConverter.convertMovement; +import static chess.domain.movement.Movement.*; +import static chess.domain.movement.MovementConverter.convertMovement; public class Pawn extends Piece { diff --git a/src/main/java/chess/model/piece/pieces/Queen.java b/src/main/java/chess/domain/piece/pieces/Queen.java similarity index 77% rename from src/main/java/chess/model/piece/pieces/Queen.java rename to src/main/java/chess/domain/piece/pieces/Queen.java index 4803ef0ea1..6fa7ec6d7e 100644 --- a/src/main/java/chess/model/piece/pieces/Queen.java +++ b/src/main/java/chess/domain/piece/pieces/Queen.java @@ -1,13 +1,13 @@ -package chess.model.piece.pieces; +package chess.domain.piece.pieces; -import static chess.model.movement.MovementConverter.convertMovement; +import static chess.domain.movement.MovementConverter.convertMovement; -import chess.model.movement.Movement; -import chess.model.movement.Path; -import chess.model.piece.Piece; -import chess.model.piece.PieceInfo; -import chess.model.position.Color; -import chess.model.position.Position; +import chess.domain.movement.Movement; +import chess.domain.movement.Path; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceInfo; +import chess.domain.position.Color; +import chess.domain.position.Position; import java.util.ArrayList; import java.util.Arrays; diff --git a/src/main/java/chess/model/piece/pieces/Rook.java b/src/main/java/chess/domain/piece/pieces/Rook.java similarity index 75% rename from src/main/java/chess/model/piece/pieces/Rook.java rename to src/main/java/chess/domain/piece/pieces/Rook.java index 732d57a0f2..c116a4c9c9 100644 --- a/src/main/java/chess/model/piece/pieces/Rook.java +++ b/src/main/java/chess/domain/piece/pieces/Rook.java @@ -1,13 +1,13 @@ -package chess.model.piece.pieces; +package chess.domain.piece.pieces; -import static chess.model.movement.MovementConverter.convertMovement; +import static chess.domain.movement.MovementConverter.convertMovement; -import chess.model.movement.Movement; -import chess.model.movement.Path; -import chess.model.piece.Piece; -import chess.model.piece.PieceInfo; -import chess.model.position.Color; -import chess.model.position.Position; +import chess.domain.movement.Movement; +import chess.domain.movement.Path; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceInfo; +import chess.domain.position.Color; +import chess.domain.position.Position; import java.util.ArrayList; import java.util.Arrays; diff --git a/src/main/java/chess/model/position/Color.java b/src/main/java/chess/domain/position/Color.java similarity index 87% rename from src/main/java/chess/model/position/Color.java rename to src/main/java/chess/domain/position/Color.java index c3171b681f..cd0312c658 100644 --- a/src/main/java/chess/model/position/Color.java +++ b/src/main/java/chess/domain/position/Color.java @@ -1,7 +1,6 @@ -package chess.model.position; +package chess.domain.position; public enum Color { - BLACK, WHITE; diff --git a/src/main/java/chess/model/position/File.java b/src/main/java/chess/domain/position/File.java similarity index 90% rename from src/main/java/chess/model/position/File.java rename to src/main/java/chess/domain/position/File.java index 621758ecfb..662d03b782 100644 --- a/src/main/java/chess/model/position/File.java +++ b/src/main/java/chess/domain/position/File.java @@ -1,6 +1,6 @@ -package chess.model.position; +package chess.domain.position; -import chess.model.ErrorMessage; +import chess.domain.ErrorMessage; import java.util.Arrays; public enum File { diff --git a/src/main/java/chess/model/position/InitialPosition.java b/src/main/java/chess/domain/position/InitialPosition.java similarity index 97% rename from src/main/java/chess/model/position/InitialPosition.java rename to src/main/java/chess/domain/position/InitialPosition.java index 892b59bbfb..9034643004 100644 --- a/src/main/java/chess/model/position/InitialPosition.java +++ b/src/main/java/chess/domain/position/InitialPosition.java @@ -1,4 +1,4 @@ -package chess.model.position; +package chess.domain.position; public enum InitialPosition { WHITE_ROOK_LEFT(1, 1), diff --git a/src/main/java/chess/model/position/Position.java b/src/main/java/chess/domain/position/Position.java similarity index 93% rename from src/main/java/chess/model/position/Position.java rename to src/main/java/chess/domain/position/Position.java index 276e5b596c..66ddd33f89 100644 --- a/src/main/java/chess/model/position/Position.java +++ b/src/main/java/chess/domain/position/Position.java @@ -1,9 +1,10 @@ -package chess.model.position; +package chess.domain.position; -import chess.model.movement.Movement; +import chess.domain.movement.Movement; import java.util.Objects; public class Position { + private final File file; private final Rank rank; diff --git a/src/main/java/chess/model/position/Rank.java b/src/main/java/chess/domain/position/Rank.java similarity index 90% rename from src/main/java/chess/model/position/Rank.java rename to src/main/java/chess/domain/position/Rank.java index c8877ce568..c67982f1ae 100644 --- a/src/main/java/chess/model/position/Rank.java +++ b/src/main/java/chess/domain/position/Rank.java @@ -1,6 +1,6 @@ -package chess.model.position; +package chess.domain.position; -import chess.model.ErrorMessage; +import chess.domain.ErrorMessage; import java.util.Arrays; public enum Rank { From c786f3d5770437b775555b9e18c0b313e0b19064 Mon Sep 17 00:00:00 2001 From: junseoplee Date: Tue, 23 Jul 2024 18:11:08 +0900 Subject: [PATCH 08/23] =?UTF-8?q?feat:=20=EA=B2=8C=EC=9E=84=EB=B3=84?= =?UTF-8?q?=EB=A1=9C=20=EA=B5=AC=EB=B6=84=ED=95=A0=20=EC=88=98=20=EC=9E=88?= =?UTF-8?q?=EB=8A=94=20ChessGame=20=ED=81=B4=EB=9E=98=EC=8A=A4=20=EA=B5=AC?= =?UTF-8?q?=ED=98=84,=20=EC=A0=80=EC=9E=A5=ED=95=A0=20=EC=88=98=20?= =?UTF-8?q?=EC=9E=88=EB=8F=84=EB=A1=9D=20=EC=83=81=ED=83=9C=EB=A5=BC=20?= =?UTF-8?q?=EB=82=98=ED=83=80=EB=82=B4=EB=8A=94=20State=20=EC=97=B4?= =?UTF-8?q?=EA=B1=B0=ED=98=95=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chess/{model => domain}/ErrorMessage.java | 7 ++- .../java/chess/domain/game/ChessGame.java | 63 +++++++++++++++++++ src/main/java/chess/domain/game/State.java | 7 +++ 3 files changed, 75 insertions(+), 2 deletions(-) rename src/main/java/chess/{model => domain}/ErrorMessage.java (87%) create mode 100644 src/main/java/chess/domain/game/ChessGame.java create mode 100644 src/main/java/chess/domain/game/State.java diff --git a/src/main/java/chess/model/ErrorMessage.java b/src/main/java/chess/domain/ErrorMessage.java similarity index 87% rename from src/main/java/chess/model/ErrorMessage.java rename to src/main/java/chess/domain/ErrorMessage.java index 7f28d8e5d8..9be80f00d2 100644 --- a/src/main/java/chess/model/ErrorMessage.java +++ b/src/main/java/chess/domain/ErrorMessage.java @@ -1,4 +1,4 @@ -package chess.model; +package chess.domain; public enum ErrorMessage { INVALID_INITIAL_COMMAND("[ERROR] 게임 시작 명령은 start, 게임 종료 명령은 end 여야 합니다."), @@ -13,7 +13,10 @@ public enum ErrorMessage { SAME_COLOR_PIECE("[ERROR] 같은 색의 말로는 이동할 수 없습니다."), SAME_POSITION("[ERROR] 출발지와 목적지가 동일하여 이동할 수 없습니다."), INVALID_MOVE_COMMAND("[ERROR] 이동은 move source 위치 target 위치여야 합니다."), - INVALID_COMMAND("[ERROR] 유효하지 않은 명령입니다."); + INVALID_COMMAND("[ERROR] 유효하지 않은 명령입니다."), + + ALREADY_RUNNING("[ERROR] 이미 진행 중인 게임입니다."), + NOT_RUNNING("[ERROR] 진행 중인 게임이 아닙니다."); private final String message; diff --git a/src/main/java/chess/domain/game/ChessGame.java b/src/main/java/chess/domain/game/ChessGame.java new file mode 100644 index 0000000000..a857ead671 --- /dev/null +++ b/src/main/java/chess/domain/game/ChessGame.java @@ -0,0 +1,63 @@ +package chess.domain.game; + +import chess.domain.ErrorMessage; +import chess.domain.board.Board; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceInfo; +import chess.domain.position.Color; +import chess.domain.position.Position; + +public class ChessGame { + + private final long id; + private State state; + private Color turn; + private final Board board; + + public ChessGame(long id, Board board, Color turn) { + this.id = id; + this.state = State.WAITING; + this.board = board; + this.turn = turn; + } + + public void start() { + if (state == State.RUNNING) { + throw new IllegalArgumentException(ErrorMessage.ALREADY_RUNNING.getMessage()); + } + this.state = State.RUNNING; + } + + public void end() { + this.state = State.FINISHED; + } + + public void movePiece(Position source, Position target) { + checkRunning(); + Piece capturedPiece = board.moveAndReturnPiece(source, target, turn); + checkKingCaptured(capturedPiece); + changeTurn(); + } + + public Double calculateScore(Color color) { + checkRunning(); + return ScoreCalculator.calculate(board.getMap(), color); + } + + private void checkRunning() { + if (state == State.RUNNING) { + return; + } + throw new IllegalArgumentException(ErrorMessage.NOT_RUNNING.getMessage()); + } + + private void checkKingCaptured(Piece capturedPiece) { + if (capturedPiece != null && capturedPiece.pieceType() == PieceInfo.KING) { + end(); + } + } + + private void changeTurn() { + turn = turn.changeTurn(); + } +} diff --git a/src/main/java/chess/domain/game/State.java b/src/main/java/chess/domain/game/State.java new file mode 100644 index 0000000000..d6b9e7bb6b --- /dev/null +++ b/src/main/java/chess/domain/game/State.java @@ -0,0 +1,7 @@ +package chess.domain.game; + +public enum State { + WAITING, + RUNNING, + FINISHED +} From 5fd16d94e30043f04090bc6b0d8a9f9d11cab9ab Mon Sep 17 00:00:00 2001 From: junseoplee Date: Tue, 23 Jul 2024 22:36:40 +0900 Subject: [PATCH 09/23] =?UTF-8?q?feat:=20DB=20=EC=97=B0=EA=B2=B0=EC=97=90?= =?UTF-8?q?=20=ED=95=84=EC=9A=94=ED=95=9C=20=EC=84=A4=EC=A0=95=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 2 ++ src/main/java/chess/dao/JdbcConnection.java | 29 +++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 src/main/java/chess/dao/JdbcConnection.java diff --git a/build.gradle b/build.gradle index 9d9f1e41f2..daa2e95f52 100644 --- a/build.gradle +++ b/build.gradle @@ -11,6 +11,8 @@ repositories { dependencies { testImplementation 'org.assertj:assertj-core:3.22.0' testImplementation 'org.junit.jupiter:junit-jupiter:5.8.2' + + runtimeOnly 'mysql:mysql-connector-java:8.0.28' } java { diff --git a/src/main/java/chess/dao/JdbcConnection.java b/src/main/java/chess/dao/JdbcConnection.java new file mode 100644 index 0000000000..0b91b87ab9 --- /dev/null +++ b/src/main/java/chess/dao/JdbcConnection.java @@ -0,0 +1,29 @@ +package chess.dao; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class JdbcConnection { + + private static Connection connection; + + private static final String SERVER = "localhost:13306"; + private static final String DATABASE = "chess"; + private static final String OPTION = "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; + private static final String USERNAME = "root"; + private static final String PASSWORD = "root"; + + static { + try { + connection = DriverManager.getConnection("jdbc:mysql://" + SERVER + "/" + DATABASE + OPTION, USERNAME, PASSWORD); + } catch (final SQLException e) { + System.err.println("DB 연결 오류:" + e.getMessage()); + e.printStackTrace(); + } + } + + public static Connection getConnection() { + return connection; + } +} From 54b66b59166dd052da87cef4672633b184c6160c Mon Sep 17 00:00:00 2001 From: junseoplee Date: Tue, 23 Jul 2024 23:01:54 +0900 Subject: [PATCH 10/23] =?UTF-8?q?feat:=20DB=20=EC=97=B0=EA=B2=B0=EC=9D=84?= =?UTF-8?q?=20=EC=9C=84=ED=95=9C=20ChessGameDao=20=EA=B8=B0=EB=8A=A5=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +- src/main/java/chess/dao/JdbcTemplate.java | 49 +++++++++++++ .../chess/dao/chessGame/ChessGameDao.java | 13 ++++ .../chess/dao/chessGame/JdbcChessGameDao.java | 69 +++++++++++++++++++ .../dao/chessGame/dto/FindResponseDto.java | 22 ++++++ .../dao/chessGame/dto/SaveRequestDto.java | 16 +++++ 6 files changed, 173 insertions(+), 2 deletions(-) create mode 100644 src/main/java/chess/dao/JdbcTemplate.java create mode 100644 src/main/java/chess/dao/chessGame/ChessGameDao.java create mode 100644 src/main/java/chess/dao/chessGame/JdbcChessGameDao.java create mode 100644 src/main/java/chess/dao/chessGame/dto/FindResponseDto.java create mode 100644 src/main/java/chess/dao/chessGame/dto/SaveRequestDto.java diff --git a/README.md b/README.md index 3ff85a5387..3e2af30158 100644 --- a/README.md +++ b/README.md @@ -56,9 +56,11 @@ - 이전에 진행하던 게임이 없다면 새로운 게임을 시작한다 - [ ] 새로하기 - 이전에 진행하던 게임이 있어도 새로운 게임을 시작한다 -- 현재 턴을 따로 저장해야한다 -> ChessController 리팩토링 + +- chessGame(id를 갖고있는<-방 번호가 됨)을 따로 저장, Turn 을 저장할 필요가 있음, 게임의 진행 상태를 저장할 필요가 있음 + - [ ] 피스를 이동할 때 마다 피스 테이블을 업데이트한다 -- [ ] 체스 게임을 저장할 수 있다 -> ChessDao +- [ ] 체스 게임을 저장할 수 있다 - [ ] 체스 게임을 찾을 수 있다 - [ ] 체스 게임을 삭제할 수 있다 diff --git a/src/main/java/chess/dao/JdbcTemplate.java b/src/main/java/chess/dao/JdbcTemplate.java new file mode 100644 index 0000000000..a0ddaf9b18 --- /dev/null +++ b/src/main/java/chess/dao/JdbcTemplate.java @@ -0,0 +1,49 @@ +package chess.dao; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public class JdbcTemplate { + + private static final int FIRST_INDEX = 1; + private final Connection connection; + + public JdbcTemplate(final Connection connection) { + this.connection = connection; + } + + public void executeUpdate(final String query, final Object... parameters) { + try (final PreparedStatement preparedStatement = connection.prepareStatement(query)) { + for (int index = FIRST_INDEX; index <= parameters.length; index++) { + preparedStatement.setObject(index, parameters[index - FIRST_INDEX]); + } + preparedStatement.executeUpdate(); + } catch (final SQLException e) { + throw new RuntimeException(e); + } + } + + public List executeQuery(final String query, final List resultParameters, + final Object... sqlParameters) { + try (final PreparedStatement preparedStatement = connection.prepareStatement(query)) { + final List result = new ArrayList<>(); + for (int index = FIRST_INDEX; index <= sqlParameters.length; index++) { + preparedStatement.setObject(index, sqlParameters[index - FIRST_INDEX]); + } + + final ResultSet resultSet = preparedStatement.executeQuery(); + while (resultSet.next()) { + for (String parameter : resultParameters) { + result.add(resultSet.getObject(parameter)); + } + } + return result; + } catch (final SQLException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/chess/dao/chessGame/ChessGameDao.java b/src/main/java/chess/dao/chessGame/ChessGameDao.java new file mode 100644 index 0000000000..b1def5861d --- /dev/null +++ b/src/main/java/chess/dao/chessGame/ChessGameDao.java @@ -0,0 +1,13 @@ +package chess.dao.chessGame; + +import chess.dao.chessGame.dto.FindResponseDto; +import chess.dao.chessGame.dto.SaveRequestDto; +import chess.domain.position.Color; + +public interface ChessGameDao { + + Long save(final SaveRequestDto saveRequestDto); + FindResponseDto findChessGameById(final long id); + void updateTurn(final long id, final Color turn); + void delete(); +} diff --git a/src/main/java/chess/dao/chessGame/JdbcChessGameDao.java b/src/main/java/chess/dao/chessGame/JdbcChessGameDao.java new file mode 100644 index 0000000000..cfb7a3c868 --- /dev/null +++ b/src/main/java/chess/dao/chessGame/JdbcChessGameDao.java @@ -0,0 +1,69 @@ +package chess.dao.chessGame; + +import chess.dao.JdbcConnection; +import chess.dao.JdbcTemplate; +import chess.dao.chessGame.dto.FindResponseDto; +import chess.dao.chessGame.dto.SaveRequestDto; +import chess.domain.position.Color; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +public class JdbcChessGameDao implements ChessGameDao { + + private static final long TEMPORARY_ID = 1; + + private final Connection connection; + private final JdbcTemplate jdbcTemplate; + + public JdbcChessGameDao() { + this.connection = JdbcConnection.getConnection(); + this.jdbcTemplate = new JdbcTemplate(connection); + } + + @Override + public Long save(final SaveRequestDto saveRequestDto) { + final String query = "INSERT INTO chess_game VALUES (?, ?)"; + try (final PreparedStatement preparedStatement = + connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) { + preparedStatement.setLong(1, TEMPORARY_ID); + preparedStatement.setString(2, saveRequestDto.getTurn().name()); + preparedStatement.executeUpdate(); + return retrieveGeneratedKey(preparedStatement); + } catch (final SQLException e) { + throw new RuntimeException(e); + } + } + + private long retrieveGeneratedKey(final PreparedStatement preparedStatement) throws SQLException { + final ResultSet resultSet = preparedStatement.getGeneratedKeys(); + resultSet.next(); + return resultSet.getLong(1); + } + + @Override + public FindResponseDto findChessGameById(final long id) { + final String query = "SELECT * FROM chess_game WHERE id = ?"; + final List resultParameters = List.of("id", "turn"); + final List result = jdbcTemplate.executeQuery(query, resultParameters, id); + return new FindResponseDto( + (Long) result.get(0), + Color.valueOf((String) result.get(1)) + ); + } + + @Override + public void updateTurn(final long id, final Color turn) { + final String query = "UPDATE chess_game SET turn = ? WHERE id = ?"; + jdbcTemplate.executeUpdate(query, turn.name(), id); + } + + @Override + public void delete() { + final String query = "DELETE FROM chess_game"; + jdbcTemplate.executeUpdate(query); + } +} diff --git a/src/main/java/chess/dao/chessGame/dto/FindResponseDto.java b/src/main/java/chess/dao/chessGame/dto/FindResponseDto.java new file mode 100644 index 0000000000..a34aecaff3 --- /dev/null +++ b/src/main/java/chess/dao/chessGame/dto/FindResponseDto.java @@ -0,0 +1,22 @@ +package chess.dao.chessGame.dto; + +import chess.domain.position.Color; + +public class FindResponseDto { + + private final Long id; + private final Color turn; + + public FindResponseDto(Long id, Color turn) { + this.id = id; + this.turn = turn; + } + + public Long getId() { + return id; + } + + public Color getTurn() { + return turn; + } +} diff --git a/src/main/java/chess/dao/chessGame/dto/SaveRequestDto.java b/src/main/java/chess/dao/chessGame/dto/SaveRequestDto.java new file mode 100644 index 0000000000..878a55a83c --- /dev/null +++ b/src/main/java/chess/dao/chessGame/dto/SaveRequestDto.java @@ -0,0 +1,16 @@ +package chess.dao.chessGame.dto; + +import chess.domain.position.Color; + +public class SaveRequestDto { + + private final Color turn; + + public SaveRequestDto(Color turn) { + this.turn = turn; + } + + public Color getTurn() { + return turn; + } +} From 9f7f78c2dcbf4173556119f93500968589a0dc94 Mon Sep 17 00:00:00 2001 From: junseoplee Date: Wed, 24 Jul 2024 02:13:15 +0900 Subject: [PATCH 11/23] =?UTF-8?q?feat:=20DB=20=EC=97=B0=EA=B2=B0=EC=9D=84?= =?UTF-8?q?=20=EC=9C=84=ED=95=9C=20PieceDao=20=EA=B8=B0=EB=8A=A5=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 10 +-- .../java/chess/dao/piece/JdbcPieceDao.java | 61 +++++++++++++++++++ src/main/java/chess/dao/piece/PieceDao.java | 14 +++++ .../java/chess/domain/piece/PieceFactory.java | 59 ++++++++++++++++++ 4 files changed, 139 insertions(+), 5 deletions(-) create mode 100644 src/main/java/chess/dao/piece/JdbcPieceDao.java create mode 100644 src/main/java/chess/dao/piece/PieceDao.java create mode 100644 src/main/java/chess/domain/piece/PieceFactory.java diff --git a/README.md b/README.md index 3e2af30158..e914e10320 100644 --- a/README.md +++ b/README.md @@ -65,19 +65,19 @@ - [ ] 체스 게임을 삭제할 수 있다 ``` -CREATE TABLE chess_games ( +CREATE TABLE chess_game ( id BIGINT NOT NULL AUTO_INCREMENT, current_turn VARCHAR(16) NOT NULL, PRIMARY KEY (id) ); -CREATE TABLE pieces ( +CREATE TABLE piece ( id BIGINT NOT NULL AUTO_INCREMENT, - game_id BIGINT NOT NULL, + chess_game_id BIGINT NOT NULL, piece_file INT NOT NULL, piece_rank INT NOT NULL, - color VARCHAR(16) NOT NULL, - type VARCHAR(16) NOT NULL, + color VARCHAR(16), + type VARCHAR(16), PRIMARY KEY (id), FOREIGN KEY (game_id) REFERENCES games(id) ); diff --git a/src/main/java/chess/dao/piece/JdbcPieceDao.java b/src/main/java/chess/dao/piece/JdbcPieceDao.java new file mode 100644 index 0000000000..059b2f3ef1 --- /dev/null +++ b/src/main/java/chess/dao/piece/JdbcPieceDao.java @@ -0,0 +1,61 @@ +package chess.dao.piece; + +import chess.dao.JdbcConnection; +import chess.dao.JdbcTemplate; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceFactory; +import chess.domain.position.Position; +import java.sql.Connection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class JdbcPieceDao implements PieceDao { + + private final Connection connection; + private final JdbcTemplate jdbcTemplate; + + public JdbcPieceDao() { + this.connection = JdbcConnection.getConnection(); + this.jdbcTemplate = new JdbcTemplate(connection); + } + + @Override + public void insert(final long chessGameId, final Position position, final Piece piece) { + final String query = "INSERT INTO piece (chess_game_id, piece_file, piece_rank, color, type) " + + "VALUES (?, ?, ?, ?, ?)"; + jdbcTemplate.executeUpdate(query, chessGameId, position.getFile(), + position.getRank(), piece.getColor().name(), piece.pieceType().name()); + } + + @Override + public void delete(final long chessGameId, final Position position) { + final String query = "DELETE FROM piece WHERE piece_file = ? AND piece_rank = ?"; + jdbcTemplate.executeUpdate(query, position.getFile(), position.getRank()); + } + + @Override + public Map putPiecesById(final long chessGameId) { + Map board = new HashMap<>(); + + final String query = "SELECT * FROM piece WHERE chess_game_id = ?"; + final List resultParameters = List.of("type", "color", "piece_file", "piece_rank"); + final List result = jdbcTemplate.executeQuery(query, resultParameters, chessGameId); + + int index = 0; + while (index < result.size()) { + final String type = (String) result.get(index++); + final String color = (String) result.get(index++); + final int file = (int) result.get(index++); + final int rank = (int) result.get(index++); + board.put(new Position(file, rank), PieceFactory.getPiece(type, color)); + } + return board; + } + + @Override + public void deleteAll() { + final String query = "DELETE FROM piece"; + jdbcTemplate.executeUpdate(query); + } +} diff --git a/src/main/java/chess/dao/piece/PieceDao.java b/src/main/java/chess/dao/piece/PieceDao.java new file mode 100644 index 0000000000..841318b3b7 --- /dev/null +++ b/src/main/java/chess/dao/piece/PieceDao.java @@ -0,0 +1,14 @@ +package chess.dao.piece; + +import chess.domain.piece.Piece; +import chess.domain.position.Position; +import java.sql.SQLException; +import java.util.Map; + +public interface PieceDao { + + void insert(long chessGameId, Position position, Piece piece); + void delete(long chessGameId, Position position); + Map putPiecesById(long chessGameId) throws SQLException; + void deleteAll(); +} diff --git a/src/main/java/chess/domain/piece/PieceFactory.java b/src/main/java/chess/domain/piece/PieceFactory.java new file mode 100644 index 0000000000..f5c37adb4e --- /dev/null +++ b/src/main/java/chess/domain/piece/PieceFactory.java @@ -0,0 +1,59 @@ +package chess.domain.piece; + +import chess.domain.piece.pieces.Bishop; +import chess.domain.piece.pieces.King; +import chess.domain.piece.pieces.Knight; +import chess.domain.piece.pieces.Pawn; +import chess.domain.piece.pieces.Queen; +import chess.domain.piece.pieces.Rook; +import chess.domain.position.Color; + +public enum PieceFactory { + PAWN { + @Override + public Piece createPiece(Color color) { + return new Pawn(color); + } + }, + ROOK { + @Override + public Piece createPiece(Color color) { + return new Rook(color); + } + }, + KNIGHT { + @Override + public Piece createPiece(Color color) { + return new Knight(color); + } + }, + BISHOP { + @Override + public Piece createPiece(Color color) { + return new Bishop(color); + } + }, + QUEEN { + @Override + public Piece createPiece(Color color) { + return new Queen(color); + } + }, + KING { + @Override + public Piece createPiece(Color color) { + return new King(color); + } + }; + + public abstract Piece createPiece(Color color); + + public static Piece getPiece(String type, String color) { + for (PieceFactory pieceFactory : PieceFactory.values()) { + if (pieceFactory.name().equalsIgnoreCase(type)) { + return pieceFactory.createPiece(Color.valueOf(color.toUpperCase())); + } + } + return null; + } +} From 037471d94756c48ce6cf8d6a82f61877649c6a43 Mon Sep 17 00:00:00 2001 From: junseoplee Date: Wed, 24 Jul 2024 02:13:15 +0900 Subject: [PATCH 12/23] =?UTF-8?q?feat:=20DB=20=EC=97=B0=EA=B2=B0=EC=9D=84?= =?UTF-8?q?=20=EC=9C=84=ED=95=9C=20PieceDao=20=EA=B8=B0=EB=8A=A5=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/dao/piece/JdbcPieceDao.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/chess/dao/piece/JdbcPieceDao.java b/src/main/java/chess/dao/piece/JdbcPieceDao.java index 059b2f3ef1..2fb2b97ce2 100644 --- a/src/main/java/chess/dao/piece/JdbcPieceDao.java +++ b/src/main/java/chess/dao/piece/JdbcPieceDao.java @@ -24,14 +24,17 @@ public JdbcPieceDao() { public void insert(final long chessGameId, final Position position, final Piece piece) { final String query = "INSERT INTO piece (chess_game_id, piece_file, piece_rank, color, type) " + "VALUES (?, ?, ?, ?, ?)"; - jdbcTemplate.executeUpdate(query, chessGameId, position.getFile(), - position.getRank(), piece.getColor().name(), piece.pieceType().name()); + jdbcTemplate.executeUpdate(query, chessGameId, + position.getFile().getValue(), + position.getRank().getValue(), + piece.getColor().name(), + piece.pieceType().name()); } @Override public void delete(final long chessGameId, final Position position) { final String query = "DELETE FROM piece WHERE piece_file = ? AND piece_rank = ?"; - jdbcTemplate.executeUpdate(query, position.getFile(), position.getRank()); + jdbcTemplate.executeUpdate(query, position.getFile().getValue(), position.getRank().getValue()); } @Override From 61d451a5444c74818f9a12dc15b91cfa0f0569b7 Mon Sep 17 00:00:00 2001 From: junseoplee Date: Thu, 25 Jul 2024 23:46:42 +0900 Subject: [PATCH 13/23] =?UTF-8?q?fix:=20DB=20=EC=97=B0=EA=B2=B0=EC=9D=84?= =?UTF-8?q?=20=EC=9C=84=ED=95=9C=20=EC=84=A4=EC=A0=95=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/dao/JdbcConnection.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/chess/dao/JdbcConnection.java b/src/main/java/chess/dao/JdbcConnection.java index 0b91b87ab9..fa902f5392 100644 --- a/src/main/java/chess/dao/JdbcConnection.java +++ b/src/main/java/chess/dao/JdbcConnection.java @@ -8,7 +8,7 @@ public class JdbcConnection { private static Connection connection; - private static final String SERVER = "localhost:13306"; + private static final String SERVER = "localhost:3306"; private static final String DATABASE = "chess"; private static final String OPTION = "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; private static final String USERNAME = "root"; From 3f07391446128f51e7d2404c9b381ec595c1d06e Mon Sep 17 00:00:00 2001 From: junseoplee Date: Thu, 25 Jul 2024 23:48:35 +0900 Subject: [PATCH 14/23] =?UTF-8?q?refactor:=20Board=20=EB=B0=98=ED=99=98?= =?UTF-8?q?=EC=9D=84=20=EC=9C=84=ED=95=9C=20=EB=A6=AC=ED=8C=A9=ED=86=A0?= =?UTF-8?q?=EB=A7=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/domain/board/Board.java | 4 ++++ .../{InitialBoard.java => BoardFactory.java} | 16 ++++++++-------- 2 files changed, 12 insertions(+), 8 deletions(-) rename src/main/java/chess/domain/board/{InitialBoard.java => BoardFactory.java} (88%) diff --git a/src/main/java/chess/domain/board/Board.java b/src/main/java/chess/domain/board/Board.java index 59773c6fcd..4823a44888 100644 --- a/src/main/java/chess/domain/board/Board.java +++ b/src/main/java/chess/domain/board/Board.java @@ -54,4 +54,8 @@ private void validatePath(Position from, Position to) { public Map getMap() { return Map.copyOf(board); } + + public Piece getPiece(Position position) { + return board.get(position); + } } diff --git a/src/main/java/chess/domain/board/InitialBoard.java b/src/main/java/chess/domain/board/BoardFactory.java similarity index 88% rename from src/main/java/chess/domain/board/InitialBoard.java rename to src/main/java/chess/domain/board/BoardFactory.java index 4e35544640..ba089e7c05 100644 --- a/src/main/java/chess/domain/board/InitialBoard.java +++ b/src/main/java/chess/domain/board/BoardFactory.java @@ -13,9 +13,9 @@ import java.util.HashMap; import java.util.Map; -public class InitialBoard { +public class BoardFactory { - public Board createInitialBoard() { + public static Board createInitialBoard() { Map board = new HashMap<>(); board.putAll(createPawn()); @@ -28,7 +28,7 @@ public Board createInitialBoard() { return new Board(board); } - private Map createPawn() { + private static Map createPawn() { Map pieceMap = new HashMap<>(); for (InitialPosition position : InitialPosition.values()) { if (position.name().startsWith("WHITE_PAWN")) { @@ -41,21 +41,21 @@ private Map createPawn() { return pieceMap; } - private Map createKing() { + private static Map createKing() { Map pieceMap = new HashMap<>(); pieceMap.put(InitialPosition.WHITE_KING.getPosition(), new King(Color.WHITE)); pieceMap.put(InitialPosition.BLACK_KING.getPosition(), new King(Color.BLACK)); return pieceMap; } - private Map createQueen() { + private static Map createQueen() { Map pieceMap = new HashMap<>(); pieceMap.put(InitialPosition.WHITE_QUEEN.getPosition(), new Queen(Color.WHITE)); pieceMap.put(InitialPosition.BLACK_QUEEN.getPosition(), new Queen(Color.BLACK)); return pieceMap; } - private Map createBishop() { + private static Map createBishop() { Map pieceMap = new HashMap<>(); pieceMap.put(InitialPosition.WHITE_BISHOP_LEFT.getPosition(), new Bishop(Color.WHITE)); pieceMap.put(InitialPosition.WHITE_BISHOP_RIGHT.getPosition(), new Bishop(Color.WHITE)); @@ -64,7 +64,7 @@ private Map createBishop() { return pieceMap; } - private Map createKnight() { + private static Map createKnight() { Map pieceMap = new HashMap<>(); pieceMap.put(InitialPosition.WHITE_KNIGHT_LEFT.getPosition(), new Knight(Color.WHITE)); pieceMap.put(InitialPosition.WHITE_KNIGHT_RIGHT.getPosition(), new Knight(Color.WHITE)); @@ -73,7 +73,7 @@ private Map createKnight() { return pieceMap; } - private Map createRook() { + private static Map createRook() { Map pieceMap = new HashMap<>(); pieceMap.put(InitialPosition.WHITE_ROOK_LEFT.getPosition(), new Rook(Color.WHITE)); pieceMap.put(InitialPosition.WHITE_ROOK_RIGHT.getPosition(), new Rook(Color.WHITE)); From a4d293e4ae71da0c71b0d024d4defed625c497f9 Mon Sep 17 00:00:00 2001 From: junseoplee Date: Thu, 25 Jul 2024 23:50:09 +0900 Subject: [PATCH 15/23] =?UTF-8?q?refactor:=20=EC=A7=84=ED=96=89=20?= =?UTF-8?q?=EC=83=81=ED=83=9C=EB=A5=BC=20=EB=B3=B4=EB=8B=A4=20=EB=AA=85?= =?UTF-8?q?=ED=99=95=ED=95=98=EA=B2=8C=20=EC=95=8C=20=EC=88=98=20=EC=9E=88?= =?UTF-8?q?=EB=8F=84=EB=A1=9D=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/chess/domain/game/ChessGame.java | 34 +++++++++++++++---- src/main/java/chess/domain/game/State.java | 7 ++-- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/src/main/java/chess/domain/game/ChessGame.java b/src/main/java/chess/domain/game/ChessGame.java index a857ead671..e81b2aa319 100644 --- a/src/main/java/chess/domain/game/ChessGame.java +++ b/src/main/java/chess/domain/game/ChessGame.java @@ -16,20 +16,24 @@ public class ChessGame { public ChessGame(long id, Board board, Color turn) { this.id = id; - this.state = State.WAITING; + this.state = State.RUN; this.board = board; this.turn = turn; } public void start() { - if (state == State.RUNNING) { - throw new IllegalArgumentException(ErrorMessage.ALREADY_RUNNING.getMessage()); + if (state == State.START) { + throw new IllegalArgumentException(ErrorMessage.ALREADY_START.getMessage()); } - this.state = State.RUNNING; + this.state = State.START; } public void end() { - this.state = State.FINISHED; + this.state = State.END; + } + + public void checkmate() { + this.state = State.CHECKMATE; } public void movePiece(Position source, Position target) { @@ -45,7 +49,7 @@ public Double calculateScore(Color color) { } private void checkRunning() { - if (state == State.RUNNING) { + if (state == State.RUN) { return; } throw new IllegalArgumentException(ErrorMessage.NOT_RUNNING.getMessage()); @@ -53,11 +57,27 @@ private void checkRunning() { private void checkKingCaptured(Piece capturedPiece) { if (capturedPiece != null && capturedPiece.pieceType() == PieceInfo.KING) { - end(); + checkmate(); } } private void changeTurn() { turn = turn.changeTurn(); } + + public Color getTurn() { + return turn; + } + + public long getId() { + return id; + } + + public Board getBoard() { + return board; + } + + public State getState() { + return state; + } } diff --git a/src/main/java/chess/domain/game/State.java b/src/main/java/chess/domain/game/State.java index d6b9e7bb6b..6a60b9836e 100644 --- a/src/main/java/chess/domain/game/State.java +++ b/src/main/java/chess/domain/game/State.java @@ -1,7 +1,8 @@ package chess.domain.game; public enum State { - WAITING, - RUNNING, - FINISHED + START, + RUN, + END, + CHECKMATE } From e20a260fece3dfb6f594d7d1389ac127438d0bf6 Mon Sep 17 00:00:00 2001 From: junseoplee Date: Thu, 25 Jul 2024 23:52:41 +0900 Subject: [PATCH 16/23] =?UTF-8?q?feat:=20DB=20=EC=97=B0=EA=B2=B0=20?= =?UTF-8?q?=EA=B8=B0=EB=8A=A5=EA=B3=BC=20=EC=BB=A8=ED=8A=B8=EB=A1=A4?= =?UTF-8?q?=EB=9F=AC=20=EC=A1=B0=EB=A6=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/ChessApplication.java | 18 +- .../chess/controller/ChessController.java | 210 +++++++++++------- .../chess/controller/command/Command.java | 24 ++ .../controller/command/InitialCommand.java | 22 ++ .../command/commands}/CommandFactory.java | 6 +- .../command/commands}/CommandLauncher.java | 2 +- .../command/commands/EndCommand.java | 6 +- .../command/commands/MoveCommand.java | 5 +- .../command/commands/StartCommand.java | 5 +- .../command/commands/StatusCommand.java | 5 +- .../java/chess/service/ChessGameService.java | 69 ++++++ src/main/java/chess/view/OutputView.java | 60 +++-- src/main/java/chess/view/Symbol.java | 8 +- .../board/BoardFactoryTest.java} | 20 +- .../{model => domain}/board/BoardTest.java | 36 +-- .../movement/MovementConverterTest.java | 6 +- .../{model => domain}/movement/PathTest.java | 4 +- .../{model => domain}/piece/PieceTest.java | 13 +- .../piece/pieces/BishopTest.java | 13 +- .../piece/pieces/KingTest.java | 18 +- .../piece/pieces/KnightTest.java | 14 +- .../piece/pieces/PawnTest.java | 28 ++- .../piece/pieces/QueenTest.java | 15 +- .../piece/pieces/RookTest.java | 14 +- .../{model => domain}/position/FileTest.java | 2 +- .../position/PositionTest.java | 6 +- .../{model => domain}/position/RankTest.java | 3 +- .../score/ScoreCalculatorTest.java | 15 +- 28 files changed, 426 insertions(+), 221 deletions(-) create mode 100644 src/main/java/chess/controller/command/Command.java create mode 100644 src/main/java/chess/controller/command/InitialCommand.java rename src/main/java/chess/{domain/command => controller/command/commands}/CommandFactory.java (89%) rename src/main/java/chess/{domain/command => controller/command/commands}/CommandLauncher.java (82%) rename src/main/java/chess/{domain => controller}/command/commands/EndCommand.java (68%) rename src/main/java/chess/{domain => controller}/command/commands/MoveCommand.java (81%) rename src/main/java/chess/{domain => controller}/command/commands/StartCommand.java (74%) rename src/main/java/chess/{domain => controller}/command/commands/StatusCommand.java (71%) create mode 100644 src/main/java/chess/service/ChessGameService.java rename src/test/java/chess/{model/board/InitialBoardTest.java => domain/board/BoardFactoryTest.java} (76%) rename src/test/java/chess/{model => domain}/board/BoardTest.java (84%) rename src/test/java/chess/{model => domain}/movement/MovementConverterTest.java (92%) rename src/test/java/chess/{model => domain}/movement/PathTest.java (94%) rename src/test/java/chess/{model => domain}/piece/PieceTest.java (86%) rename src/test/java/chess/{model => domain}/piece/pieces/BishopTest.java (73%) rename src/test/java/chess/{model => domain}/piece/pieces/KingTest.java (63%) rename src/test/java/chess/{model => domain}/piece/pieces/KnightTest.java (71%) rename src/test/java/chess/{model => domain}/piece/pieces/PawnTest.java (79%) rename src/test/java/chess/{model => domain}/piece/pieces/QueenTest.java (70%) rename src/test/java/chess/{model => domain}/piece/pieces/RookTest.java (70%) rename src/test/java/chess/{model => domain}/position/FileTest.java (95%) rename src/test/java/chess/{model => domain}/position/PositionTest.java (94%) rename src/test/java/chess/{model => domain}/position/RankTest.java (84%) rename src/test/java/chess/{model => domain}/score/ScoreCalculatorTest.java (93%) diff --git a/src/main/java/chess/ChessApplication.java b/src/main/java/chess/ChessApplication.java index e7a0206c7b..68027d6b6b 100644 --- a/src/main/java/chess/ChessApplication.java +++ b/src/main/java/chess/ChessApplication.java @@ -1,22 +1,24 @@ package chess; import chess.controller.ChessController; -import chess.model.command.CommandFactory; -import chess.model.board.InitialBoard; +import chess.dao.chessGame.JdbcChessGameDao; +import chess.dao.piece.JdbcPieceDao; +import chess.service.ChessGameService; import chess.view.InputView; import chess.view.OutputView; +import java.sql.SQLException; public class ChessApplication { - public static void main(String[] args) { + public static void main(String[] args) throws SQLException { + final JdbcChessGameDao chessGameDao = new JdbcChessGameDao(); + final JdbcPieceDao PieceDao = new JdbcPieceDao(); + final ChessGameService chessGameService = new ChessGameService(chessGameDao, PieceDao); InputView inputView = new InputView(); OutputView outputView = new OutputView(); - CommandFactory commandFactory = new CommandFactory(); - InitialBoard initialBoard = new InitialBoard(); + final ChessController chessController = new ChessController(chessGameService, inputView, outputView); - ChessController chessController = new ChessController(inputView, outputView, commandFactory, - initialBoard); - chessController.runChess(); + chessController.run(); } } diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index c988f1c4b3..b97900396e 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -1,113 +1,163 @@ package chess.controller; -import chess.model.command.CommandFactory; -import chess.model.command.CommandLauncher; -import chess.model.ErrorMessage; -import chess.model.board.Board; -import chess.model.board.InitialBoard; -import chess.model.piece.Piece; -import chess.model.piece.PieceInfo; -import chess.model.position.Color; -import chess.model.position.Position; -import chess.model.score.ScoreCalculator; +import chess.controller.command.Command; +import chess.controller.command.InitialCommand; +import chess.domain.game.ChessGame; +import chess.domain.game.State; +import chess.domain.position.Color; +import chess.domain.position.Position; +import chess.service.ChessGameService; import chess.view.InputView; import chess.view.OutputView; +import java.sql.SQLException; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; public class ChessController { + private static final int COMMAND_INDEX = 0; + private static final int SOURCE_POSITION_INDEX = 1; + private static final int TARGET_POSITION_INDEX = 2; + + private final Map>> commands = + new EnumMap<>(Command.class); + private final ChessGameService chessGameService; + private final InputView inputView; private final OutputView outputView; - private final CommandFactory commandFactory; - private final Board board; - private Color currentTurn; - private boolean isRunning; - public ChessController(InputView inputView, OutputView outputView, CommandFactory commandFactory, InitialBoard initialBoard) { + public ChessController(ChessGameService chessGameService, InputView inputView, + OutputView outputView) { + putCommands(); + this.chessGameService = chessGameService; this.inputView = inputView; this.outputView = outputView; - this.commandFactory = commandFactory; - this.board = initialBoard.createInitialBoard(); - this.currentTurn = Color.WHITE; - this.isRunning = true; - } - - public void runChess() { - outputView.printStartMessage(); - CommandLauncher receivedCommand = null; - - while (receivedCommand == null) { - try { - String initialCommandInput = inputView.receiveCommand(); - receivedCommand = commandFactory.createCommand(initialCommandInput); - if (receivedCommand.validateInitialCommandType()) { - break; - } - System.out.println(ErrorMessage.INVALID_INITIAL_COMMAND.getMessage()); - receivedCommand = null; - } catch (IllegalArgumentException exception) { - System.out.println(exception.getMessage()); - } + } + + private void putCommands() { + commands.put(Command.START, (chessGame, ignored) -> start(chessGame)); + commands.put(Command.END, (chessGame, ignored) -> end(chessGame)); + commands.put(Command.STATUS, (chessGame, ignored) -> status(chessGame)); + commands.put(Command.MOVE, this::movePiece); + } + + private void start(ChessGame chessGame) { + chessGame.start(); + } + + private void end(ChessGame chessGame) { + chessGame.end(); + } + + private void status(ChessGame chessGame) { + final Double whiteScore = chessGame.calculateScore(Color.WHITE); + final Double blackScore = chessGame.calculateScore(Color.BLACK); + printScoreAndWinningColor(whiteScore, blackScore); + } + + private void movePiece(ChessGame chessGame, List commandParts) { + final Position source = parsePosition(commandParts.get(SOURCE_POSITION_INDEX)); + final Position target = parsePosition(commandParts.get(TARGET_POSITION_INDEX)); + chessGame.movePiece(source, target); + chessGameService.updatePiece(chessGame, source, target); + } + + public void run() throws SQLException { + ChessGame chessGame = initializeChessGame(receiveInitialCommand()); + + while (isRunnable(chessGame)) { + printChessBoard(chessGame); + executeCommand(chessGame); } + processIfKingCaptured(chessGame); + } + + private boolean isRunnable(ChessGame chessGame) { + return chessGame.getState().equals(State.RUN) + || chessGame.getState().equals(State.START); + } - receivedCommand.execute(this); - - while (isRunning) { - try { - String commandInput = inputView.receiveCommand(); - receivedCommand = commandFactory.createCommand(commandInput); - if (receivedCommand.validateStatusCommandType()) { - receivedCommand.execute(this); - continue; // 명령이 status 일 경우 턴을 바꾸지 않음 - } - receivedCommand.execute(this); - currentTurn = currentTurn.changeTurn(); - } catch (IllegalArgumentException exception) { - System.out.println(exception.getMessage()); - } + private void processIfKingCaptured(final ChessGame chessGame) { + if (chessGame.getState().equals(State.CHECKMATE)) { + final Color winner = chessGame.getTurn(); + outputView.printWinningColor(winner); } } - public void startGame() { - outputView.printBoard(board.getMap()); + private void executeCommand(ChessGame chessGame) { + try { + outputView.printCommandMessage(); + final List commandParts = List.of(inputView.receiveCommand().split(" ")); + final Command command = Command.findCommand(commandParts.get(COMMAND_INDEX)); + commands.get(command).accept(chessGame, commandParts); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e); + executeCommand(chessGame); + } } - public void endGame() { - isRunning = false; + private void printChessBoard(final ChessGame chessGame) { + if (chessGame.getState().equals(State.RUN)) { + outputView.printBoard(chessGame.getBoard().getMap()); + } } - public void movePiece(Position source, Position target) { - Piece capturedPiece = board.move(source, target, currentTurn); - checkAndHandleKingCapture(capturedPiece, currentTurn); - outputView.printBoard(board.getMap()); + private InitialCommand receiveInitialCommand() { + try { + outputView.printInitialMessage(); + final String command = inputView.receiveCommand(); + return InitialCommand.findCommand(command); + } catch (IllegalArgumentException e) { + outputView.printErrorMessage(e); + return receiveInitialCommand(); + } } - public void calculateAndPrintCurrentTurnScore() { - double score = ScoreCalculator.calculate(board.getMap(), currentTurn); - outputView.printCurrentTurnScore(currentTurn, score); + private ChessGame initializeChessGame(InitialCommand command) throws SQLException { + ChessGame chessGame = findChessGameIfContinue(command); + + if (chessGame == null) { + outputView.printNewGameMessage(); + chessGameService.deleteChessGame(); + chessGame = chessGameService.initializeChessGame(); + } + return chessGame; } - public void printScoreAndWinningColor() { - double currentTurnScore = ScoreCalculator.calculate(board.getMap(), currentTurn); - double opponentScore = ScoreCalculator.calculate(board.getMap(), currentTurn.changeTurn()); - outputView.printCurrentScore(currentTurn, currentTurnScore); - outputView.printCurrentScore(currentTurn.changeTurn(), opponentScore); - if (currentTurnScore > opponentScore) { - outputView.printWinningColor(currentTurn); + private ChessGame findChessGameIfContinue(final InitialCommand command) throws SQLException { + ChessGame chessGame = null; + if (command.equals(InitialCommand.CONTINUE)) { + chessGame = chessGameService.findChessGame(); + printContinueMessage(chessGame); } - if (opponentScore > currentTurnScore) { - outputView.printWinningColor(currentTurn.changeTurn()); + return chessGame; + } + + private void printContinueMessage(final ChessGame chessGame) { + if (chessGame == null) { + outputView.printNoExistsRunningGameMessage(); } - if (currentTurnScore == opponentScore) { + outputView.printContinueMessage(); + } + + private void printScoreAndWinningColor(Double whiteScore, Double blackScore) { + outputView.printScore(whiteScore, blackScore); + if (whiteScore > blackScore) { + outputView.printWinningColor(Color.WHITE); + } + if (whiteScore < blackScore) { + outputView.printWinningColor(Color.BLACK); + } + if (whiteScore.equals(blackScore)) { outputView.printDraw(); } } - private void checkAndHandleKingCapture(Piece capturedPiece, Color currentTurn) { - if (capturedPiece != null && capturedPiece.pieceType() == PieceInfo.KING) { - endGame(); - double currentTurnScore = ScoreCalculator.calculate(board.getMap(), currentTurn); - outputView.printCurrentScore(currentTurn, currentTurnScore); - outputView.printWinningColor(currentTurn); - } + private static Position parsePosition(String position) { + int file = position.charAt(0) - 'a' + 1; + int rank = position.charAt(1) - '0'; + return new Position(file, rank); // 생성자에 1~8 유효성 검사가 있다 } } diff --git a/src/main/java/chess/controller/command/Command.java b/src/main/java/chess/controller/command/Command.java new file mode 100644 index 0000000000..454ef1c402 --- /dev/null +++ b/src/main/java/chess/controller/command/Command.java @@ -0,0 +1,24 @@ +package chess.controller.command; + +import chess.domain.ErrorMessage; +import java.util.Arrays; + +public enum Command { + START("start"), + END("end"), + STATUS("status"), + MOVE("move"); + + private final String command; + + Command(final String command) { + this.command = command; + } + + public static Command findCommand(final String value) { + return Arrays.stream(values()) + .filter(command -> command.command.equals(value)) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(ErrorMessage.INVALID_COMMAND.getMessage())); + } +} diff --git a/src/main/java/chess/controller/command/InitialCommand.java b/src/main/java/chess/controller/command/InitialCommand.java new file mode 100644 index 0000000000..46c257e4cd --- /dev/null +++ b/src/main/java/chess/controller/command/InitialCommand.java @@ -0,0 +1,22 @@ +package chess.controller.command; + +import chess.domain.ErrorMessage; +import java.util.Arrays; + +public enum InitialCommand { + NEW("new"), + CONTINUE("continue"); + + private final String command; + + InitialCommand(String command) { + this.command = command; + } + + public static InitialCommand findCommand(final String value) { + return Arrays.stream(values()) + .filter(command -> command.command.equals(value)) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(ErrorMessage.INVALID_COMMAND.getMessage())); + } +} diff --git a/src/main/java/chess/domain/command/CommandFactory.java b/src/main/java/chess/controller/command/commands/CommandFactory.java similarity index 89% rename from src/main/java/chess/domain/command/CommandFactory.java rename to src/main/java/chess/controller/command/commands/CommandFactory.java index 1afde2ae15..8bae6d7b63 100644 --- a/src/main/java/chess/domain/command/CommandFactory.java +++ b/src/main/java/chess/controller/command/commands/CommandFactory.java @@ -1,10 +1,6 @@ -package chess.domain.command; +package chess.controller.command.commands; -import chess.domain.command.commands.EndCommand; -import chess.domain.command.commands.MoveCommand; -import chess.domain.command.commands.StartCommand; import chess.domain.ErrorMessage; -import chess.domain.command.commands.StatusCommand; import chess.domain.position.Position; import java.util.HashMap; import java.util.List; diff --git a/src/main/java/chess/domain/command/CommandLauncher.java b/src/main/java/chess/controller/command/commands/CommandLauncher.java similarity index 82% rename from src/main/java/chess/domain/command/CommandLauncher.java rename to src/main/java/chess/controller/command/commands/CommandLauncher.java index bff74b588e..0b055570d1 100644 --- a/src/main/java/chess/domain/command/CommandLauncher.java +++ b/src/main/java/chess/controller/command/commands/CommandLauncher.java @@ -1,4 +1,4 @@ -package chess.domain.command; +package chess.controller.command.commands; import chess.controller.ChessController; diff --git a/src/main/java/chess/domain/command/commands/EndCommand.java b/src/main/java/chess/controller/command/commands/EndCommand.java similarity index 68% rename from src/main/java/chess/domain/command/commands/EndCommand.java rename to src/main/java/chess/controller/command/commands/EndCommand.java index 3cbfe99ec4..1d81d9e2ad 100644 --- a/src/main/java/chess/domain/command/commands/EndCommand.java +++ b/src/main/java/chess/controller/command/commands/EndCommand.java @@ -1,14 +1,12 @@ -package chess.domain.command.commands; +package chess.controller.command.commands; import chess.controller.ChessController; -import chess.domain.command.CommandLauncher; public class EndCommand implements CommandLauncher { @Override public void execute(ChessController controller) { - controller.printScoreAndWinningColor(); - controller.endGame(); + // end } @Override diff --git a/src/main/java/chess/domain/command/commands/MoveCommand.java b/src/main/java/chess/controller/command/commands/MoveCommand.java similarity index 81% rename from src/main/java/chess/domain/command/commands/MoveCommand.java rename to src/main/java/chess/controller/command/commands/MoveCommand.java index c48538e22e..9927024e5a 100644 --- a/src/main/java/chess/domain/command/commands/MoveCommand.java +++ b/src/main/java/chess/controller/command/commands/MoveCommand.java @@ -1,7 +1,6 @@ -package chess.domain.command.commands; +package chess.controller.command.commands; import chess.controller.ChessController; -import chess.domain.command.CommandLauncher; import chess.domain.position.Position; public class MoveCommand implements CommandLauncher { @@ -16,7 +15,7 @@ public MoveCommand(Position source, Position target) { @Override public void execute(ChessController controller) { - controller.movePiece(source, target); + // move } @Override diff --git a/src/main/java/chess/domain/command/commands/StartCommand.java b/src/main/java/chess/controller/command/commands/StartCommand.java similarity index 74% rename from src/main/java/chess/domain/command/commands/StartCommand.java rename to src/main/java/chess/controller/command/commands/StartCommand.java index 65434f84eb..0731a7883a 100644 --- a/src/main/java/chess/domain/command/commands/StartCommand.java +++ b/src/main/java/chess/controller/command/commands/StartCommand.java @@ -1,13 +1,12 @@ -package chess.domain.command.commands; +package chess.controller.command.commands; import chess.controller.ChessController; -import chess.domain.command.CommandLauncher; public class StartCommand implements CommandLauncher { @Override public void execute(ChessController controller) { - controller.startGame(); + // start } @Override diff --git a/src/main/java/chess/domain/command/commands/StatusCommand.java b/src/main/java/chess/controller/command/commands/StatusCommand.java similarity index 71% rename from src/main/java/chess/domain/command/commands/StatusCommand.java rename to src/main/java/chess/controller/command/commands/StatusCommand.java index 9bd7ecd360..2d1e998ca8 100644 --- a/src/main/java/chess/domain/command/commands/StatusCommand.java +++ b/src/main/java/chess/controller/command/commands/StatusCommand.java @@ -1,13 +1,12 @@ -package chess.domain.command.commands; +package chess.controller.command.commands; import chess.controller.ChessController; -import chess.domain.command.CommandLauncher; public class StatusCommand implements CommandLauncher { @Override public void execute(ChessController controller) { - controller.calculateAndPrintCurrentTurnScore(); + // calculate } @Override diff --git a/src/main/java/chess/service/ChessGameService.java b/src/main/java/chess/service/ChessGameService.java new file mode 100644 index 0000000000..fd3925293c --- /dev/null +++ b/src/main/java/chess/service/ChessGameService.java @@ -0,0 +1,69 @@ +package chess.service; + +import chess.dao.chessGame.ChessGameDao; +import chess.dao.chessGame.dto.FindResponseDto; +import chess.dao.chessGame.dto.SaveRequestDto; +import chess.dao.piece.PieceDao; +import chess.domain.ErrorMessage; +import chess.domain.board.Board; +import chess.domain.board.BoardFactory; +import chess.domain.game.ChessGame; +import chess.domain.piece.Piece; +import chess.domain.position.Color; +import chess.domain.position.Position; +import java.sql.SQLException; +import java.util.Map; + +public class ChessGameService { + + private static final long TEMPORAL_ID = 1; + + private final ChessGameDao chessGameDao; + private final PieceDao pieceDao; + + public ChessGameService(final ChessGameDao chessGameDao, final PieceDao pieceDao) { + this.chessGameDao = chessGameDao; + this.pieceDao = pieceDao; + } + + public ChessGame findChessGame() throws SQLException { + final FindResponseDto findResponseDto = chessGameDao.findChessGameById(TEMPORAL_ID); + if (findResponseDto == null) { + return null; + } + return new ChessGame(findResponseDto.getId(), + new Board(pieceDao.putPiecesById(TEMPORAL_ID)), findResponseDto.getTurn()); + } + + public ChessGame initializeChessGame() { + Color turn = Color.WHITE; + final Long id = chessGameDao.save(new SaveRequestDto(turn)); + final ChessGame chessGame = new ChessGame(id, BoardFactory.createInitialBoard(), turn); + final Map board = chessGame.getBoard().getMap(); + + for (final Map.Entry entry : board.entrySet()) { + pieceDao.insert(id, entry.getKey(), entry.getValue()); + } + return chessGame; + } + + public void updatePiece(final ChessGame chessGame, final Position sourcePosition, final Position targetPosition) { + final Piece piece = findSourcePiece(chessGame, sourcePosition); + if (piece == null) { + return; + } + pieceDao.delete(chessGame.getId(), targetPosition); + pieceDao.insert(chessGame.getId(), targetPosition, piece); + pieceDao.delete(chessGame.getId(), sourcePosition); + } + + private Piece findSourcePiece(final ChessGame chessGame, final Position sourcePosition) { + final Board board = chessGame.getBoard(); + return board.getPiece(sourcePosition); + } + + public void deleteChessGame() { + chessGameDao.delete(); + pieceDao.deleteAll(); + } +} diff --git a/src/main/java/chess/view/OutputView.java b/src/main/java/chess/view/OutputView.java index c9ed823c60..2e129ea9bb 100644 --- a/src/main/java/chess/view/OutputView.java +++ b/src/main/java/chess/view/OutputView.java @@ -1,10 +1,10 @@ package chess.view; -import chess.model.piece.Piece; -import chess.model.position.Color; -import chess.model.position.File; -import chess.model.position.Position; -import chess.model.position.Rank; +import chess.domain.piece.Piece; +import chess.domain.position.Color; +import chess.domain.position.File; +import chess.domain.position.Position; +import chess.domain.position.Rank; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -17,11 +17,17 @@ public class OutputView { private static final int BOARD_SIZE = 8; private static final int INDEX_OFFSET = 1; - public void printStartMessage() { + public void printInitialMessage() { System.out.println("> 체스 게임을 시작합니다."); + System.out.println("> 이어하기 : continue"); + System.out.println("> 새로하기 : new"); + } + + public void printCommandMessage() { System.out.println("> 게임 시작 : start"); System.out.println("> 게임 종료 : end"); System.out.println("> 게임 이동 : move source 위치 target 위치 - 예. move b2 b3"); + System.out.println("> 점수 출력 : status"); } public void printBoard(final Map boardMap) { @@ -31,12 +37,36 @@ public void printBoard(final Map boardMap) { chessBoard.stream() .map(board -> String.join("", board)) .forEach(System.out::println); + } + + public void printScore(final Double whiteScore, final Double blackScore) { + System.out.println("White Score: " + whiteScore); + System.out.println("Black Score: " + blackScore); + } + + public void printWinningColor(Color currentTurn) { + System.out.println("Winning Color: " + currentTurn); + } + + public void printDraw() { + System.out.println("Draw"); + } + + public void printErrorMessage(final Exception e) { + System.out.println(e.getMessage()); System.out.print(System.lineSeparator()); } - public void printCurrentTurnScore(Color currentTurn, double score) { - System.out.println("Current turn: " + currentTurn); - System.out.println("Score: " + score); + public void printNewGameMessage() { + System.out.println("새로운 게임을 시작합니다."); + } + + public void printContinueMessage() { + System.out.println("진행 중인 게임을 이어합니다."); + } + + public void printNoExistsRunningGameMessage() { + System.out.println("진행 중인 게임이 없어 이어할 수 없습니다."); } private void assignSymbols(final Map boardMap, final List> chessBoard) { @@ -58,16 +88,4 @@ private List> createEmptyBoard() { .mapToObj(it -> new ArrayList<>(Collections.nCopies(BOARD_SIZE, Symbol.EMPTY.getSymbol()))) .collect(Collectors.toList()); } - - public void printCurrentScore(Color currentTurn, double score) { - System.out.println("Color: " + currentTurn + ", Score: " + score); - } - - public void printWinningColor(Color currentTurn) { - System.out.println("Winning Color: " + currentTurn); - } - - public void printDraw() { - System.out.println("Draw"); - } } diff --git a/src/main/java/chess/view/Symbol.java b/src/main/java/chess/view/Symbol.java index 9c797ab125..4e6797a066 100644 --- a/src/main/java/chess/view/Symbol.java +++ b/src/main/java/chess/view/Symbol.java @@ -1,9 +1,9 @@ package chess.view; -import chess.model.ErrorMessage; -import chess.model.piece.Piece; -import chess.model.piece.pieces.*; -import chess.model.position.Color; +import chess.domain.ErrorMessage; +import chess.domain.piece.Piece; +import chess.domain.piece.pieces.*; +import chess.domain.position.Color; public enum Symbol { KING("k", King.class), diff --git a/src/test/java/chess/model/board/InitialBoardTest.java b/src/test/java/chess/domain/board/BoardFactoryTest.java similarity index 76% rename from src/test/java/chess/model/board/InitialBoardTest.java rename to src/test/java/chess/domain/board/BoardFactoryTest.java index 074a9e3bd5..be268ac643 100644 --- a/src/test/java/chess/model/board/InitialBoardTest.java +++ b/src/test/java/chess/domain/board/BoardFactoryTest.java @@ -1,9 +1,9 @@ -package chess.model.board; +package chess.domain.board; -import chess.model.piece.Piece; -import chess.model.piece.pieces.*; -import chess.model.position.Color; -import chess.model.position.Position; +import chess.domain.piece.Piece; +import chess.domain.piece.pieces.*; +import chess.domain.position.Color; +import chess.domain.position.Position; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -11,13 +11,13 @@ import java.util.Map; -public class InitialBoardTest { +public class BoardFactoryTest { @Test @DisplayName("초기 보드에는 정확히 32개의 말이 있어야 한다") public void 초기_보드에는_정확히_32개의_말이_있어야_한다() { - InitialBoard initialBoard = new InitialBoard(); - Board board = initialBoard.createInitialBoard(); + BoardFactory boardFactory = new BoardFactory(); + Board board = boardFactory.createInitialBoard(); Map boardMap = board.getMap(); assertEquals(32, boardMap.size()); @@ -26,8 +26,8 @@ public class InitialBoardTest { @Test @DisplayName("초기 보드에는 각 말의 정확한 수가 있어야 한다") public void 초기_보드에는_각_말의_정확한_수가_있어야_한다() { - InitialBoard initialBoard = new InitialBoard(); - Board board = initialBoard.createInitialBoard(); + BoardFactory boardFactory = new BoardFactory(); + Board board = boardFactory.createInitialBoard(); Map boardMap = board.getMap(); long whitePawns = boardMap.values().stream().filter(piece -> piece instanceof Pawn && piece.getColor() == Color.WHITE).count(); diff --git a/src/test/java/chess/model/board/BoardTest.java b/src/test/java/chess/domain/board/BoardTest.java similarity index 84% rename from src/test/java/chess/model/board/BoardTest.java rename to src/test/java/chess/domain/board/BoardTest.java index 9c9e5b112d..feb2f4c155 100644 --- a/src/test/java/chess/model/board/BoardTest.java +++ b/src/test/java/chess/domain/board/BoardTest.java @@ -1,17 +1,17 @@ -package chess.model.board; +package chess.domain.board; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import chess.model.piece.Piece; -import chess.model.piece.PieceInfo; -import chess.model.piece.pieces.King; -import chess.model.piece.pieces.Pawn; -import chess.model.piece.pieces.Rook; -import chess.model.position.Color; -import chess.model.position.InitialPosition; -import chess.model.position.Position; -import chess.model.ErrorMessage; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceInfo; +import chess.domain.piece.pieces.King; +import chess.domain.piece.pieces.Pawn; +import chess.domain.piece.pieces.Rook; +import chess.domain.position.Color; +import chess.domain.position.InitialPosition; +import chess.domain.position.Position; +import chess.domain.ErrorMessage; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.BeforeEach; @@ -52,7 +52,7 @@ void setUp() { Position to = new Position(1, 2); // when & then - assertThatThrownBy(() -> board.move(from, to, Color.WHITE)) + assertThatThrownBy(() -> board.moveAndReturnPiece(from, to, Color.WHITE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(ErrorMessage.NO_PIECE_AT_SOURCE.getMessage()); } @@ -66,7 +66,7 @@ void setUp() { initialBoard.put(from, new Pawn(Color.BLACK)); // when & then - assertThatThrownBy(() -> board.move(from, to, Color.WHITE)) + assertThatThrownBy(() -> board.moveAndReturnPiece(from, to, Color.WHITE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(ErrorMessage.INVALID_TURN.getMessage()); } @@ -81,7 +81,7 @@ void setUp() { initialBoard.put(to, new Pawn(Color.WHITE)); // when & then - assertThatThrownBy(() -> board.move(from, to, Color.WHITE)) + assertThatThrownBy(() -> board.moveAndReturnPiece(from, to, Color.WHITE)) .isInstanceOf(IllegalArgumentException.class); } @@ -94,7 +94,7 @@ void setUp() { initialBoard.put(from, new King(Color.WHITE)); // when - board.move(from, to, Color.WHITE); + board.moveAndReturnPiece(from, to, Color.WHITE); Map retrievedMap = board.getMap(); // then @@ -112,7 +112,7 @@ void setUp() { initialBoard.put(new Position(1, 2), new Pawn(Color.WHITE)); // when & then - assertThatThrownBy(() -> board.move(from, to, Color.WHITE)) + assertThatThrownBy(() -> board.moveAndReturnPiece(from, to, Color.WHITE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(ErrorMessage.HAS_OBSTACLE.getMessage()); } @@ -126,7 +126,7 @@ void setUp() { initialBoard.put(from, new Pawn(Color.WHITE)); // when - board.move(from, to, Color.WHITE); + board.moveAndReturnPiece(from, to, Color.WHITE); Map retrievedMap = board.getMap(); // then @@ -144,7 +144,7 @@ void setUp() { initialBoard.put(to, new Pawn(Color.BLACK)); //when - board.move(from, to, Color.WHITE); + board.moveAndReturnPiece(from, to, Color.WHITE); Map retrievedMap = board.getMap(); //then @@ -163,7 +163,7 @@ void setUp() { initialBoard.put(to, new King(Color.BLACK)); // when - Piece capturedPiece = board.move(from, to, Color.WHITE); + Piece capturedPiece = board.moveAndReturnPiece(from, to, Color.WHITE); // then assertThat(capturedPiece.pieceType()).isEqualTo(PieceInfo.KING); diff --git a/src/test/java/chess/model/movement/MovementConverterTest.java b/src/test/java/chess/domain/movement/MovementConverterTest.java similarity index 92% rename from src/test/java/chess/model/movement/MovementConverterTest.java rename to src/test/java/chess/domain/movement/MovementConverterTest.java index d295b165fa..6c66487442 100644 --- a/src/test/java/chess/model/movement/MovementConverterTest.java +++ b/src/test/java/chess/domain/movement/MovementConverterTest.java @@ -1,7 +1,7 @@ -package chess.model.movement; +package chess.domain.movement; -import chess.model.position.Position; -import chess.model.ErrorMessage; +import chess.domain.position.Position; +import chess.domain.ErrorMessage; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; diff --git a/src/test/java/chess/model/movement/PathTest.java b/src/test/java/chess/domain/movement/PathTest.java similarity index 94% rename from src/test/java/chess/model/movement/PathTest.java rename to src/test/java/chess/domain/movement/PathTest.java index 9a6516b2af..37465ff2d8 100644 --- a/src/test/java/chess/model/movement/PathTest.java +++ b/src/test/java/chess/domain/movement/PathTest.java @@ -1,8 +1,8 @@ -package chess.model.movement; +package chess.domain.movement; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; -import chess.model.position.Position; +import chess.domain.position.Position; import java.util.List; import java.util.Set; import org.junit.jupiter.api.DisplayName; diff --git a/src/test/java/chess/model/piece/PieceTest.java b/src/test/java/chess/domain/piece/PieceTest.java similarity index 86% rename from src/test/java/chess/model/piece/PieceTest.java rename to src/test/java/chess/domain/piece/PieceTest.java index 192210d36d..f20568b3ff 100644 --- a/src/test/java/chess/model/piece/PieceTest.java +++ b/src/test/java/chess/domain/piece/PieceTest.java @@ -1,14 +1,15 @@ -package chess.model.piece; +package chess.domain.piece; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; -import chess.model.movement.Movement; -import chess.model.movement.Path; -import chess.model.position.Color; -import chess.model.position.Position; +import chess.domain.movement.Movement; +import chess.domain.movement.Path; +import chess.domain.position.Color; +import chess.domain.position.Position; import java.util.Arrays; import java.util.List; +import java.util.Map; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -58,7 +59,7 @@ public TestPiece(Color color) { } @Override - public Path findPath(Position from, Position to) { + public Path findPath(Position from, Position to, Map board) { // 테스트 목적으로 간단히 작성 return new Path(List.of(to)); } diff --git a/src/test/java/chess/model/piece/pieces/BishopTest.java b/src/test/java/chess/domain/piece/pieces/BishopTest.java similarity index 73% rename from src/test/java/chess/model/piece/pieces/BishopTest.java rename to src/test/java/chess/domain/piece/pieces/BishopTest.java index 84ce79a4da..d728f410de 100644 --- a/src/test/java/chess/model/piece/pieces/BishopTest.java +++ b/src/test/java/chess/domain/piece/pieces/BishopTest.java @@ -1,11 +1,13 @@ -package chess.model.piece.pieces; +package chess.domain.piece.pieces; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; -import chess.model.position.Color; -import chess.model.position.Position; -import chess.model.ErrorMessage; +import chess.domain.board.Board; +import chess.domain.board.BoardFactory; +import chess.domain.position.Color; +import chess.domain.position.Position; +import chess.domain.ErrorMessage; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -31,9 +33,10 @@ class BishopTest { Bishop bishop = new Bishop(Color.WHITE); Position from = new Position(4, 4); Position to = new Position(4, 6); + Board board = BoardFactory.createInitialBoard(); // when & then - assertThatThrownBy(() -> bishop.findPath(from, to)) + assertThatThrownBy(() -> bishop.findPath(from, to, board.getMap())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(ErrorMessage.INVALID_DIRECTION.getMessage()); } diff --git a/src/test/java/chess/model/piece/pieces/KingTest.java b/src/test/java/chess/domain/piece/pieces/KingTest.java similarity index 63% rename from src/test/java/chess/model/piece/pieces/KingTest.java rename to src/test/java/chess/domain/piece/pieces/KingTest.java index ca5fe04d1f..7f7e36d038 100644 --- a/src/test/java/chess/model/piece/pieces/KingTest.java +++ b/src/test/java/chess/domain/piece/pieces/KingTest.java @@ -1,11 +1,14 @@ -package chess.model.piece.pieces; +package chess.domain.piece.pieces; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import chess.model.position.Color; -import chess.model.position.Position; -import chess.model.ErrorMessage; +import chess.domain.board.BoardFactory; +import chess.domain.piece.Piece; +import chess.domain.position.Color; +import chess.domain.position.Position; +import chess.domain.ErrorMessage; +import java.util.Map; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -18,7 +21,7 @@ class KingTest { Color color = Color.WHITE; //when - King king =new King(color); + King king = new King(color); //then assertThat(king.getColor()).isEqualTo(color); @@ -31,10 +34,11 @@ class KingTest { King king = new King(Color.WHITE); Position from = new Position(4, 4); Position to = new Position(6, 6); + Map board = BoardFactory.createInitialBoard().getMap(); // when & then - assertThatThrownBy(() -> king.findPath(from, to)) - .isInstanceOf(IllegalStateException.class) + assertThatThrownBy(() -> king.findPath(from, to, board)) + .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(ErrorMessage.INVALID_DIRECTION.getMessage()); } } diff --git a/src/test/java/chess/model/piece/pieces/KnightTest.java b/src/test/java/chess/domain/piece/pieces/KnightTest.java similarity index 71% rename from src/test/java/chess/model/piece/pieces/KnightTest.java rename to src/test/java/chess/domain/piece/pieces/KnightTest.java index 58b780a528..91d599a477 100644 --- a/src/test/java/chess/model/piece/pieces/KnightTest.java +++ b/src/test/java/chess/domain/piece/pieces/KnightTest.java @@ -1,11 +1,14 @@ -package chess.model.piece.pieces; +package chess.domain.piece.pieces; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import chess.model.position.Color; -import chess.model.position.Position; -import chess.model.ErrorMessage; +import chess.domain.board.BoardFactory; +import chess.domain.piece.Piece; +import chess.domain.position.Color; +import chess.domain.position.Position; +import chess.domain.ErrorMessage; +import java.util.Map; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -31,9 +34,10 @@ class KnightTest { Knight knight = new Knight(Color.WHITE); Position from = new Position(4, 4); Position to = new Position(6, 6); + Map board = BoardFactory.createInitialBoard().getMap(); // when & then - assertThatThrownBy(() -> knight.findPath(from, to)) + assertThatThrownBy(() -> knight.findPath(from, to, board)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(ErrorMessage.INVALID_DIRECTION.getMessage()); } diff --git a/src/test/java/chess/model/piece/pieces/PawnTest.java b/src/test/java/chess/domain/piece/pieces/PawnTest.java similarity index 79% rename from src/test/java/chess/model/piece/pieces/PawnTest.java rename to src/test/java/chess/domain/piece/pieces/PawnTest.java index b7bfb4167d..db881ae031 100644 --- a/src/test/java/chess/model/piece/pieces/PawnTest.java +++ b/src/test/java/chess/domain/piece/pieces/PawnTest.java @@ -1,12 +1,15 @@ -package chess.model.piece.pieces; +package chess.domain.piece.pieces; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import chess.model.movement.Path; -import chess.model.position.Color; -import chess.model.position.Position; -import chess.model.ErrorMessage; +import chess.domain.board.BoardFactory; +import chess.domain.movement.Path; +import chess.domain.piece.Piece; +import chess.domain.position.Color; +import chess.domain.position.Position; +import chess.domain.ErrorMessage; +import java.util.Map; import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -38,9 +41,10 @@ class PawnTest { Pawn pawn = new Pawn(color); Position from = new Position(fromFile, fromRank); Position to = new Position(toFile, toRank); + Map board = BoardFactory.createInitialBoard().getMap(); // when - Path path = pawn.findPath(from, to); + Path path = pawn.findPath(from, to, board); // then assertThat(path) @@ -59,9 +63,10 @@ class PawnTest { Pawn pawn = new Pawn(color); Position from = new Position(fromFile, fromRank); Position to = new Position(toFile, toRank); + Map board = BoardFactory.createInitialBoard().getMap(); // when - Path path = pawn.findPath(from, to); + Path path = pawn.findPath(from, to, board); // then assertThat(path) @@ -84,9 +89,10 @@ class PawnTest { Pawn pawn = new Pawn(color); Position from = new Position(fromFile, fromRank); Position to = new Position(toFile, toRank); + Map board = BoardFactory.createInitialBoard().getMap(); // when - Path path = pawn.findPath(from, to); + Path path = pawn.findPath(from, to, board); // then assertThat(path) @@ -101,9 +107,10 @@ class PawnTest { Pawn pawn = new Pawn(Color.WHITE); Position from = new Position(2, 3); Position to = new Position(2, 2); + Map board = BoardFactory.createInitialBoard().getMap(); // when & then - assertThatThrownBy(() -> pawn.findPath(from, to)) + assertThatThrownBy(() -> pawn.findPath(from, to, board)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(ErrorMessage.INVALID_DIRECTION.getMessage()); } @@ -115,9 +122,10 @@ class PawnTest { Pawn pawn = new Pawn(Color.WHITE); Position from = new Position(2, 3); Position to = new Position(2, 5); + Map board = BoardFactory.createInitialBoard().getMap(); // when & then - assertThatThrownBy(() -> pawn.findPath(from, to)) + assertThatThrownBy(() -> pawn.findPath(from, to, board)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(ErrorMessage.INVALID_DIRECTION.getMessage()); } diff --git a/src/test/java/chess/model/piece/pieces/QueenTest.java b/src/test/java/chess/domain/piece/pieces/QueenTest.java similarity index 70% rename from src/test/java/chess/model/piece/pieces/QueenTest.java rename to src/test/java/chess/domain/piece/pieces/QueenTest.java index 58e7827393..120436f79d 100644 --- a/src/test/java/chess/model/piece/pieces/QueenTest.java +++ b/src/test/java/chess/domain/piece/pieces/QueenTest.java @@ -1,11 +1,14 @@ -package chess.model.piece.pieces; +package chess.domain.piece.pieces; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import chess.model.position.Color; -import chess.model.position.Position; -import chess.model.ErrorMessage; +import chess.domain.board.BoardFactory; +import chess.domain.piece.Piece; +import chess.domain.position.Color; +import chess.domain.position.Position; +import chess.domain.ErrorMessage; +import java.util.Map; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -31,8 +34,10 @@ class QueenTest { Queen queen = new Queen(Color.WHITE); Position from = new Position(4, 4); Position to = new Position(6, 5); + Map board = BoardFactory.createInitialBoard().getMap(); + // when & then - assertThatThrownBy(() -> queen.findPath(from, to)) + assertThatThrownBy(() -> queen.findPath(from, to, board)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(ErrorMessage.INVALID_DIRECTION.getMessage()); } diff --git a/src/test/java/chess/model/piece/pieces/RookTest.java b/src/test/java/chess/domain/piece/pieces/RookTest.java similarity index 70% rename from src/test/java/chess/model/piece/pieces/RookTest.java rename to src/test/java/chess/domain/piece/pieces/RookTest.java index 64cd4b76f1..8c108e3186 100644 --- a/src/test/java/chess/model/piece/pieces/RookTest.java +++ b/src/test/java/chess/domain/piece/pieces/RookTest.java @@ -1,11 +1,14 @@ -package chess.model.piece.pieces; +package chess.domain.piece.pieces; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import chess.model.position.Color; -import chess.model.position.Position; -import chess.model.ErrorMessage; +import chess.domain.board.BoardFactory; +import chess.domain.piece.Piece; +import chess.domain.position.Color; +import chess.domain.position.Position; +import chess.domain.ErrorMessage; +import java.util.Map; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -31,9 +34,10 @@ class RookTest { Rook rook = new Rook(Color.WHITE); Position from = new Position(4, 4); Position to = new Position(6, 5); + Map board = BoardFactory.createInitialBoard().getMap(); //when & then - assertThatThrownBy(() -> rook.findPath(from, to)) + assertThatThrownBy(() -> rook.findPath(from, to, board)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(ErrorMessage.INVALID_DIRECTION.getMessage()); } diff --git a/src/test/java/chess/model/position/FileTest.java b/src/test/java/chess/domain/position/FileTest.java similarity index 95% rename from src/test/java/chess/model/position/FileTest.java rename to src/test/java/chess/domain/position/FileTest.java index e72be0f560..a5a3f70846 100644 --- a/src/test/java/chess/model/position/FileTest.java +++ b/src/test/java/chess/domain/position/FileTest.java @@ -1,4 +1,4 @@ -package chess.model.position; +package chess.domain.position; import static org.assertj.core.api.Assertions.assertThatThrownBy; diff --git a/src/test/java/chess/model/position/PositionTest.java b/src/test/java/chess/domain/position/PositionTest.java similarity index 94% rename from src/test/java/chess/model/position/PositionTest.java rename to src/test/java/chess/domain/position/PositionTest.java index 39691fc813..5e46750b4e 100644 --- a/src/test/java/chess/model/position/PositionTest.java +++ b/src/test/java/chess/domain/position/PositionTest.java @@ -1,10 +1,10 @@ -package chess.model.position; +package chess.domain.position; -import static chess.model.movement.MovementConverter.convertMovement; +import static chess.domain.movement.MovementConverter.convertMovement; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; -import chess.model.movement.Movement; +import chess.domain.movement.Movement; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; diff --git a/src/test/java/chess/model/position/RankTest.java b/src/test/java/chess/domain/position/RankTest.java similarity index 84% rename from src/test/java/chess/model/position/RankTest.java rename to src/test/java/chess/domain/position/RankTest.java index 282c2e2aa1..3ab9ebbec6 100644 --- a/src/test/java/chess/model/position/RankTest.java +++ b/src/test/java/chess/domain/position/RankTest.java @@ -1,7 +1,6 @@ -package chess.model.position; +package chess.domain.position; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; -import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; diff --git a/src/test/java/chess/model/score/ScoreCalculatorTest.java b/src/test/java/chess/domain/score/ScoreCalculatorTest.java similarity index 93% rename from src/test/java/chess/model/score/ScoreCalculatorTest.java rename to src/test/java/chess/domain/score/ScoreCalculatorTest.java index 9b73f44e44..8c5c52992d 100644 --- a/src/test/java/chess/model/score/ScoreCalculatorTest.java +++ b/src/test/java/chess/domain/score/ScoreCalculatorTest.java @@ -1,10 +1,11 @@ -package chess.model.score; - -import chess.model.board.Board; -import chess.model.piece.Piece; -import chess.model.piece.pieces.*; -import chess.model.position.Color; -import chess.model.position.Position; +package chess.domain.score; + +import chess.domain.board.Board; +import chess.domain.game.ScoreCalculator; +import chess.domain.piece.Piece; +import chess.domain.piece.pieces.*; +import chess.domain.position.Color; +import chess.domain.position.Position; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; From 80b7e4763609e0aca8929864a87e47148ec19aab Mon Sep 17 00:00:00 2001 From: junseoplee Date: Thu, 25 Jul 2024 23:53:54 +0900 Subject: [PATCH 17/23] =?UTF-8?q?docs:=20=EA=B8=B0=EB=8A=A5=20=EC=9A=94?= =?UTF-8?q?=EA=B5=AC=20=EC=82=AC=ED=95=AD=20=EB=B0=8F=20=EC=97=90=EB=9F=AC?= =?UTF-8?q?=EB=A9=94=EC=84=B8=EC=A7=80=20=EC=97=85=EB=8D=B0=EC=9D=B4?= =?UTF-8?q?=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 21 +++++++++---------- .../controller/command/InitialCommand.java | 2 +- src/main/java/chess/domain/ErrorMessage.java | 4 ++-- 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index e914e10320..a043f85db9 100644 --- a/README.md +++ b/README.md @@ -50,24 +50,24 @@ - [x] end 명령어를 입력하면 각자의 점수와 승리 팀을 출력한다 - [x] 점수를 계산해서 점수가 높은 팀이 승리한다 - **DB 연결** -- [ ] 애플리케이션을 재시작하더라도 이전에 하던 체스 게임을 다시 시작할 수 있어야 한다 - - [ ] 이어하기 +- [x] 애플리케이션을 재시작하더라도 이전에 하던 체스 게임을 다시 시작할 수 있어야 한다 + - [x] 이어하기 - 이전에 진행하던 게임이 있다면 이어서 게임을 시작한다 - 이전에 진행하던 게임이 없다면 새로운 게임을 시작한다 - - [ ] 새로하기 + - [x] 새로하기 - 이전에 진행하던 게임이 있어도 새로운 게임을 시작한다 -- chessGame(id를 갖고있는<-방 번호가 됨)을 따로 저장, Turn 을 저장할 필요가 있음, 게임의 진행 상태를 저장할 필요가 있음 +- chessGame 을 따로 저장, Turn 을 저장할 필요가 있음, 게임의 진행 상태를 저장할 필요가 있음 -- [ ] 피스를 이동할 때 마다 피스 테이블을 업데이트한다 -- [ ] 체스 게임을 저장할 수 있다 -- [ ] 체스 게임을 찾을 수 있다 -- [ ] 체스 게임을 삭제할 수 있다 +- [x] 피스를 이동할 때 마다 피스 테이블을 업데이트한다 +- [x] 체스 게임을 저장할 수 있다 +- [x] 체스 게임을 찾을 수 있다 +- [x] 체스 게임을 삭제할 수 있다 ``` CREATE TABLE chess_game ( id BIGINT NOT NULL AUTO_INCREMENT, - current_turn VARCHAR(16) NOT NULL, + turn VARCHAR(16) NOT NULL, PRIMARY KEY (id) ); @@ -78,8 +78,7 @@ CREATE TABLE piece ( piece_rank INT NOT NULL, color VARCHAR(16), type VARCHAR(16), - PRIMARY KEY (id), - FOREIGN KEY (game_id) REFERENCES games(id) + PRIMARY KEY (id) ); ``` diff --git a/src/main/java/chess/controller/command/InitialCommand.java b/src/main/java/chess/controller/command/InitialCommand.java index 46c257e4cd..3a160b448f 100644 --- a/src/main/java/chess/controller/command/InitialCommand.java +++ b/src/main/java/chess/controller/command/InitialCommand.java @@ -17,6 +17,6 @@ public static InitialCommand findCommand(final String value) { return Arrays.stream(values()) .filter(command -> command.command.equals(value)) .findAny() - .orElseThrow(() -> new IllegalArgumentException(ErrorMessage.INVALID_COMMAND.getMessage())); + .orElseThrow(() -> new IllegalArgumentException(ErrorMessage.INVALID_INITIAL_COMMAND.getMessage())); } } diff --git a/src/main/java/chess/domain/ErrorMessage.java b/src/main/java/chess/domain/ErrorMessage.java index 9be80f00d2..9543760975 100644 --- a/src/main/java/chess/domain/ErrorMessage.java +++ b/src/main/java/chess/domain/ErrorMessage.java @@ -1,7 +1,7 @@ package chess.domain; public enum ErrorMessage { - INVALID_INITIAL_COMMAND("[ERROR] 게임 시작 명령은 start, 게임 종료 명령은 end 여야 합니다."), + INVALID_INITIAL_COMMAND("[ERROR] 이어하기는 continue, 새로하기는 new 입니다."), MISMATCH_FILE_ARGUMENT("[ERROR] 잘못된 파일 규격입니다."), MISMATCH_RANK_ARGUMENT("[ERROR] 잘못된 랭크 규격입니다."), MISMATCH_SYMBOL("[ERROR] 잘못된 피스 타입입니다."), @@ -15,7 +15,7 @@ public enum ErrorMessage { INVALID_MOVE_COMMAND("[ERROR] 이동은 move source 위치 target 위치여야 합니다."), INVALID_COMMAND("[ERROR] 유효하지 않은 명령입니다."), - ALREADY_RUNNING("[ERROR] 이미 진행 중인 게임입니다."), + ALREADY_START("[ERROR] 이미 진행 중인 게임입니다."), NOT_RUNNING("[ERROR] 진행 중인 게임이 아닙니다."); private final String message; From a3ac67f358f6c76b4c006bc01310867f31b91111 Mon Sep 17 00:00:00 2001 From: junseoplee Date: Fri, 26 Jul 2024 01:52:22 +0900 Subject: [PATCH 18/23] =?UTF-8?q?fix:=20=EA=B8=B0=EC=A1=B4=20=EA=B2=8C?= =?UTF-8?q?=EC=9E=84=EC=9D=B4=20=EC=A0=95=EC=83=81=EC=A0=81=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EB=B6=88=EB=9F=AC=EC=99=80=EC=A7=80=EC=A7=80=20?= =?UTF-8?q?=EC=95=8A=EB=8D=98=20=EC=98=A4=EB=A5=98=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/chess/controller/ChessController.java | 15 +++++---------- src/main/java/chess/domain/game/ChessGame.java | 10 +++++----- src/main/java/chess/domain/game/State.java | 6 +++--- src/main/java/chess/service/ChessGameService.java | 13 +++---------- 4 files changed, 16 insertions(+), 28 deletions(-) diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index b97900396e..0df4f9edb4 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -45,6 +45,7 @@ private void putCommands() { private void start(ChessGame chessGame) { chessGame.start(); + outputView.printBoard(chessGame.getBoard().getMap()); } private void end(ChessGame chessGame) { @@ -62,21 +63,21 @@ private void movePiece(ChessGame chessGame, List commandParts) { final Position target = parsePosition(commandParts.get(TARGET_POSITION_INDEX)); chessGame.movePiece(source, target); chessGameService.updatePiece(chessGame, source, target); + outputView.printBoard(chessGame.getBoard().getMap()); } public void run() throws SQLException { ChessGame chessGame = initializeChessGame(receiveInitialCommand()); while (isRunnable(chessGame)) { - printChessBoard(chessGame); executeCommand(chessGame); } processIfKingCaptured(chessGame); } private boolean isRunnable(ChessGame chessGame) { - return chessGame.getState().equals(State.RUN) - || chessGame.getState().equals(State.START); + return chessGame.getState().equals(State.RUNNING) + || chessGame.getState().equals(State.WAITING); } private void processIfKingCaptured(final ChessGame chessGame) { @@ -98,12 +99,6 @@ private void executeCommand(ChessGame chessGame) { } } - private void printChessBoard(final ChessGame chessGame) { - if (chessGame.getState().equals(State.RUN)) { - outputView.printBoard(chessGame.getBoard().getMap()); - } - } - private InitialCommand receiveInitialCommand() { try { outputView.printInitialMessage(); @@ -117,7 +112,7 @@ private InitialCommand receiveInitialCommand() { private ChessGame initializeChessGame(InitialCommand command) throws SQLException { ChessGame chessGame = findChessGameIfContinue(command); - + // new 입력하면 메서드가 작동하지 않아 null 로 반환된다 if (chessGame == null) { outputView.printNewGameMessage(); chessGameService.deleteChessGame(); diff --git a/src/main/java/chess/domain/game/ChessGame.java b/src/main/java/chess/domain/game/ChessGame.java index e81b2aa319..6010da0ced 100644 --- a/src/main/java/chess/domain/game/ChessGame.java +++ b/src/main/java/chess/domain/game/ChessGame.java @@ -16,20 +16,20 @@ public class ChessGame { public ChessGame(long id, Board board, Color turn) { this.id = id; - this.state = State.RUN; + this.state = State.WAITING; this.board = board; this.turn = turn; } public void start() { - if (state == State.START) { + if (state == State.RUNNING) { throw new IllegalArgumentException(ErrorMessage.ALREADY_START.getMessage()); } - this.state = State.START; + this.state = State.RUNNING; } public void end() { - this.state = State.END; + this.state = State.ENDED; } public void checkmate() { @@ -49,7 +49,7 @@ public Double calculateScore(Color color) { } private void checkRunning() { - if (state == State.RUN) { + if (state == State.RUNNING) { return; } throw new IllegalArgumentException(ErrorMessage.NOT_RUNNING.getMessage()); diff --git a/src/main/java/chess/domain/game/State.java b/src/main/java/chess/domain/game/State.java index 6a60b9836e..a94e58f3ba 100644 --- a/src/main/java/chess/domain/game/State.java +++ b/src/main/java/chess/domain/game/State.java @@ -1,8 +1,8 @@ package chess.domain.game; public enum State { - START, - RUN, - END, + WAITING, + RUNNING, + ENDED, CHECKMATE } diff --git a/src/main/java/chess/service/ChessGameService.java b/src/main/java/chess/service/ChessGameService.java index fd3925293c..a7bcf5baae 100644 --- a/src/main/java/chess/service/ChessGameService.java +++ b/src/main/java/chess/service/ChessGameService.java @@ -4,7 +4,6 @@ import chess.dao.chessGame.dto.FindResponseDto; import chess.dao.chessGame.dto.SaveRequestDto; import chess.dao.piece.PieceDao; -import chess.domain.ErrorMessage; import chess.domain.board.Board; import chess.domain.board.BoardFactory; import chess.domain.game.ChessGame; @@ -48,18 +47,12 @@ public ChessGame initializeChessGame() { } public void updatePiece(final ChessGame chessGame, final Position sourcePosition, final Position targetPosition) { - final Piece piece = findSourcePiece(chessGame, sourcePosition); - if (piece == null) { - return; - } + final Piece piece = chessGame.getBoard().getPiece(targetPosition); + pieceDao.delete(chessGame.getId(), targetPosition); pieceDao.insert(chessGame.getId(), targetPosition, piece); pieceDao.delete(chessGame.getId(), sourcePosition); - } - - private Piece findSourcePiece(final ChessGame chessGame, final Position sourcePosition) { - final Board board = chessGame.getBoard(); - return board.getPiece(sourcePosition); + chessGameDao.updateTurn(chessGame.getId(), chessGame.getTurn()); } public void deleteChessGame() { From ddfb9611b9dcf7aa4c06c231b936162e6d9ac23c Mon Sep 17 00:00:00 2001 From: junseoplee Date: Mon, 29 Jul 2024 17:05:41 +0900 Subject: [PATCH 19/23] =?UTF-8?q?refactor:=20=EB=AA=85=EB=A0=B9=EC=96=B4?= =?UTF-8?q?=EB=A5=BC=20=EB=8B=A4=EB=A3=A8=EB=8A=94=20=EC=B1=85=EC=9E=84?= =?UTF-8?q?=EC=9D=84=20=EC=BB=A8=ED=8A=B8=EB=A1=A4=EB=9F=AC=EC=97=90?= =?UTF-8?q?=EC=84=9C=20=EB=B6=84=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gradlew.bat | 4 +- src/main/java/chess/ChessApplication.java | 6 +- .../chess/controller/ChessController.java | 136 ++---------------- .../controller/command/CommandFactory.java | 46 ++++++ .../{Command.java => CommandType.java} | 12 +- ...alCommand.java => InitialCommandType.java} | 6 +- .../controller/command/commands/Command.java | 10 ++ .../command/commands/CommandFactory.java | 54 ------- .../command/commands/CommandLauncher.java | 9 -- .../command/commands/ContinueCommand.java | 23 +++ .../command/commands/EndCommand.java | 20 +-- .../command/commands/MoveCommand.java | 45 ++++-- .../command/commands/NewCommand.java | 21 +++ .../command/commands/StartCommand.java | 22 +-- .../command/commands/StatusCommand.java | 37 +++-- .../java/chess/service/ChessGameService.java | 3 - src/main/java/chess/view/InputView.java | 13 +- src/main/java/chess/view/OutputView.java | 38 ++--- 18 files changed, 238 insertions(+), 267 deletions(-) create mode 100644 src/main/java/chess/controller/command/CommandFactory.java rename src/main/java/chess/controller/command/{Command.java => CommandType.java} (60%) rename src/main/java/chess/controller/command/{InitialCommand.java => InitialCommandType.java} (76%) create mode 100644 src/main/java/chess/controller/command/commands/Command.java delete mode 100644 src/main/java/chess/controller/command/commands/CommandFactory.java delete mode 100644 src/main/java/chess/controller/command/commands/CommandLauncher.java create mode 100644 src/main/java/chess/controller/command/commands/ContinueCommand.java create mode 100644 src/main/java/chess/controller/command/commands/NewCommand.java diff --git a/gradlew.bat b/gradlew.bat index 6689b85bee..563ba037e2 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -44,7 +44,7 @@ set JAVA_EXE=java.exe if %ERRORLEVEL% equ 0 goto execute echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo ERROR: JAVA_HOME is not set and no 'java' commandType could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. @@ -66,7 +66,7 @@ echo location of your Java installation. goto fail :execute -@rem Setup the command line +@rem Setup the commandType line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar diff --git a/src/main/java/chess/ChessApplication.java b/src/main/java/chess/ChessApplication.java index 68027d6b6b..3a2a036a1a 100644 --- a/src/main/java/chess/ChessApplication.java +++ b/src/main/java/chess/ChessApplication.java @@ -4,8 +4,6 @@ import chess.dao.chessGame.JdbcChessGameDao; import chess.dao.piece.JdbcPieceDao; import chess.service.ChessGameService; -import chess.view.InputView; -import chess.view.OutputView; import java.sql.SQLException; public class ChessApplication { @@ -15,9 +13,7 @@ public static void main(String[] args) throws SQLException { final JdbcChessGameDao chessGameDao = new JdbcChessGameDao(); final JdbcPieceDao PieceDao = new JdbcPieceDao(); final ChessGameService chessGameService = new ChessGameService(chessGameDao, PieceDao); - InputView inputView = new InputView(); - OutputView outputView = new OutputView(); - final ChessController chessController = new ChessController(chessGameService, inputView, outputView); + final ChessController chessController = new ChessController(chessGameService); chessController.run(); } diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index 0df4f9edb4..fe1b9104fb 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -1,158 +1,52 @@ package chess.controller; -import chess.controller.command.Command; -import chess.controller.command.InitialCommand; +import chess.controller.command.CommandFactory; +import chess.controller.command.commands.Command; import chess.domain.game.ChessGame; import chess.domain.game.State; -import chess.domain.position.Color; -import chess.domain.position.Position; import chess.service.ChessGameService; import chess.view.InputView; import chess.view.OutputView; import java.sql.SQLException; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; -import java.util.function.BiConsumer; public class ChessController { - private static final int COMMAND_INDEX = 0; - private static final int SOURCE_POSITION_INDEX = 1; - private static final int TARGET_POSITION_INDEX = 2; - - private final Map>> commands = - new EnumMap<>(Command.class); private final ChessGameService chessGameService; - private final InputView inputView; - private final OutputView outputView; - - public ChessController(ChessGameService chessGameService, InputView inputView, - OutputView outputView) { - putCommands(); + public ChessController(ChessGameService chessGameService) { this.chessGameService = chessGameService; - this.inputView = inputView; - this.outputView = outputView; - } - - private void putCommands() { - commands.put(Command.START, (chessGame, ignored) -> start(chessGame)); - commands.put(Command.END, (chessGame, ignored) -> end(chessGame)); - commands.put(Command.STATUS, (chessGame, ignored) -> status(chessGame)); - commands.put(Command.MOVE, this::movePiece); - } - - private void start(ChessGame chessGame) { - chessGame.start(); - outputView.printBoard(chessGame.getBoard().getMap()); - } - - private void end(ChessGame chessGame) { - chessGame.end(); - } - - private void status(ChessGame chessGame) { - final Double whiteScore = chessGame.calculateScore(Color.WHITE); - final Double blackScore = chessGame.calculateScore(Color.BLACK); - printScoreAndWinningColor(whiteScore, blackScore); - } - - private void movePiece(ChessGame chessGame, List commandParts) { - final Position source = parsePosition(commandParts.get(SOURCE_POSITION_INDEX)); - final Position target = parsePosition(commandParts.get(TARGET_POSITION_INDEX)); - chessGame.movePiece(source, target); - chessGameService.updatePiece(chessGame, source, target); - outputView.printBoard(chessGame.getBoard().getMap()); } public void run() throws SQLException { - ChessGame chessGame = initializeChessGame(receiveInitialCommand()); + ChessGame chessGame = executeInitialCommandAndFetchChessGame(); while (isRunnable(chessGame)) { executeCommand(chessGame); } - processIfKingCaptured(chessGame); - } - - private boolean isRunnable(ChessGame chessGame) { - return chessGame.getState().equals(State.RUNNING) - || chessGame.getState().equals(State.WAITING); - } - - private void processIfKingCaptured(final ChessGame chessGame) { - if (chessGame.getState().equals(State.CHECKMATE)) { - final Color winner = chessGame.getTurn(); - outputView.printWinningColor(winner); - } } private void executeCommand(ChessGame chessGame) { try { - outputView.printCommandMessage(); - final List commandParts = List.of(inputView.receiveCommand().split(" ")); - final Command command = Command.findCommand(commandParts.get(COMMAND_INDEX)); - commands.get(command).accept(chessGame, commandParts); + Command command = CommandFactory.createCommand(chessGame, InputView.receiveCommand()); + command.execute(chessGameService); } catch (IllegalArgumentException e) { - outputView.printErrorMessage(e); + OutputView.printErrorMessage(e); executeCommand(chessGame); } } - private InitialCommand receiveInitialCommand() { + private ChessGame executeInitialCommandAndFetchChessGame() throws SQLException { try { - outputView.printInitialMessage(); - final String command = inputView.receiveCommand(); - return InitialCommand.findCommand(command); + Command command = CommandFactory.createInitialCommand(InputView.receiveInitialCommand()); + return command.initializeChessGame(chessGameService); } catch (IllegalArgumentException e) { - outputView.printErrorMessage(e); - return receiveInitialCommand(); - } - } - - private ChessGame initializeChessGame(InitialCommand command) throws SQLException { - ChessGame chessGame = findChessGameIfContinue(command); - // new 입력하면 메서드가 작동하지 않아 null 로 반환된다 - if (chessGame == null) { - outputView.printNewGameMessage(); - chessGameService.deleteChessGame(); - chessGame = chessGameService.initializeChessGame(); - } - return chessGame; - } - - private ChessGame findChessGameIfContinue(final InitialCommand command) throws SQLException { - ChessGame chessGame = null; - if (command.equals(InitialCommand.CONTINUE)) { - chessGame = chessGameService.findChessGame(); - printContinueMessage(chessGame); - } - return chessGame; - } - - private void printContinueMessage(final ChessGame chessGame) { - if (chessGame == null) { - outputView.printNoExistsRunningGameMessage(); + OutputView.printErrorMessage(e); + return executeInitialCommandAndFetchChessGame(); } - outputView.printContinueMessage(); } - private void printScoreAndWinningColor(Double whiteScore, Double blackScore) { - outputView.printScore(whiteScore, blackScore); - if (whiteScore > blackScore) { - outputView.printWinningColor(Color.WHITE); - } - if (whiteScore < blackScore) { - outputView.printWinningColor(Color.BLACK); - } - if (whiteScore.equals(blackScore)) { - outputView.printDraw(); - } - } - - private static Position parsePosition(String position) { - int file = position.charAt(0) - 'a' + 1; - int rank = position.charAt(1) - '0'; - return new Position(file, rank); // 생성자에 1~8 유효성 검사가 있다 + private boolean isRunnable(ChessGame chessGame) { + return chessGame.getState().equals(State.RUNNING) + || chessGame.getState().equals(State.WAITING); } } diff --git a/src/main/java/chess/controller/command/CommandFactory.java b/src/main/java/chess/controller/command/CommandFactory.java new file mode 100644 index 0000000000..f7279d538e --- /dev/null +++ b/src/main/java/chess/controller/command/CommandFactory.java @@ -0,0 +1,46 @@ +package chess.controller.command; + +import chess.controller.command.commands.Command; +import chess.controller.command.commands.ContinueCommand; +import chess.controller.command.commands.EndCommand; +import chess.controller.command.commands.MoveCommand; +import chess.controller.command.commands.NewCommand; +import chess.controller.command.commands.StartCommand; +import chess.controller.command.commands.StatusCommand; +import chess.domain.game.ChessGame; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; + +public class CommandFactory { + + private static final int COMMAND_INDEX = 0; + + private static final Map, Command>> COMMAND_TYPES = + new EnumMap<>(CommandType.class); + + private static final Map INITIAL_COMMAND_TYPES = new EnumMap<>(CommandType.class); + + static { + COMMAND_TYPES.put(CommandType.START, (chessGame, ignored) -> new StartCommand(chessGame)); + COMMAND_TYPES.put(CommandType.END, (chessGame, ignored) -> new EndCommand(chessGame)); + COMMAND_TYPES.put(CommandType.STATUS, (chessGame, ignored) -> new StatusCommand(chessGame)); + COMMAND_TYPES.put(CommandType.MOVE, MoveCommand::new); + + INITIAL_COMMAND_TYPES.put(CommandType.NEW, new NewCommand()); + INITIAL_COMMAND_TYPES.put(CommandType.CONTINUE, new ContinueCommand()); + } + + public static Command createCommand(ChessGame chessGame, String command) { + final List commandParts = List.of(command.split(" ")); + final CommandType commandType = CommandType.findCommand(commandParts.get(COMMAND_INDEX)); + return COMMAND_TYPES.get(commandType).apply(chessGame, commandParts); + } + + public static Command createInitialCommand(String command) { + final List commandParts = List.of(command.split(" ")); + final CommandType commandType = CommandType.findCommand(commandParts.get(COMMAND_INDEX)); + return INITIAL_COMMAND_TYPES.get(commandType); + } +} diff --git a/src/main/java/chess/controller/command/Command.java b/src/main/java/chess/controller/command/CommandType.java similarity index 60% rename from src/main/java/chess/controller/command/Command.java rename to src/main/java/chess/controller/command/CommandType.java index 454ef1c402..82e0f10c46 100644 --- a/src/main/java/chess/controller/command/Command.java +++ b/src/main/java/chess/controller/command/CommandType.java @@ -3,21 +3,23 @@ import chess.domain.ErrorMessage; import java.util.Arrays; -public enum Command { +public enum CommandType { START("start"), END("end"), STATUS("status"), - MOVE("move"); + MOVE("move"), + NEW("new"), + CONTINUE("continue"); private final String command; - Command(final String command) { + CommandType(final String command) { this.command = command; } - public static Command findCommand(final String value) { + public static CommandType findCommand(final String value) { return Arrays.stream(values()) - .filter(command -> command.command.equals(value)) + .filter(commandType -> commandType.command.equals(value)) .findAny() .orElseThrow(() -> new IllegalArgumentException(ErrorMessage.INVALID_COMMAND.getMessage())); } diff --git a/src/main/java/chess/controller/command/InitialCommand.java b/src/main/java/chess/controller/command/InitialCommandType.java similarity index 76% rename from src/main/java/chess/controller/command/InitialCommand.java rename to src/main/java/chess/controller/command/InitialCommandType.java index 3a160b448f..729a053590 100644 --- a/src/main/java/chess/controller/command/InitialCommand.java +++ b/src/main/java/chess/controller/command/InitialCommandType.java @@ -3,17 +3,17 @@ import chess.domain.ErrorMessage; import java.util.Arrays; -public enum InitialCommand { +public enum InitialCommandType { NEW("new"), CONTINUE("continue"); private final String command; - InitialCommand(String command) { + InitialCommandType(String command) { this.command = command; } - public static InitialCommand findCommand(final String value) { + public static InitialCommandType findCommand(final String value) { return Arrays.stream(values()) .filter(command -> command.command.equals(value)) .findAny() diff --git a/src/main/java/chess/controller/command/commands/Command.java b/src/main/java/chess/controller/command/commands/Command.java new file mode 100644 index 0000000000..7c8ef2a18e --- /dev/null +++ b/src/main/java/chess/controller/command/commands/Command.java @@ -0,0 +1,10 @@ +package chess.controller.command.commands; + +import chess.domain.game.ChessGame; +import chess.service.ChessGameService; +import java.sql.SQLException; + +public interface Command { + void execute(final ChessGameService chessGameService); + ChessGame initializeChessGame(final ChessGameService chessGameService) throws SQLException; +} diff --git a/src/main/java/chess/controller/command/commands/CommandFactory.java b/src/main/java/chess/controller/command/commands/CommandFactory.java deleted file mode 100644 index 8bae6d7b63..0000000000 --- a/src/main/java/chess/controller/command/commands/CommandFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -package chess.controller.command.commands; - -import chess.domain.ErrorMessage; -import chess.domain.position.Position; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Function; - -public class CommandFactory { - - public static final String START_COMMAND = "start"; - public static final String END_COMMAND = "end"; - public static final String MOVE_COMMAND = "move"; - public static final String STATUS_COMMAND = "status"; - private static final int COMMAND_INDEX = 0; - private static final int SOURCE_POSITION_INDEX = 1; - private static final int TARGET_POSITION_INDEX = 2; - private static final int MOVE_COMMAND_PARTS_COUNT = 3; - - private static final Map, CommandLauncher>> - commandMap = new HashMap<>(); - - static { - commandMap.put(START_COMMAND, parts -> new StartCommand()); - commandMap.put(END_COMMAND, parts -> new EndCommand()); - commandMap.put(MOVE_COMMAND, parts -> { - if (parts.size() != MOVE_COMMAND_PARTS_COUNT) { - throw new IllegalArgumentException(ErrorMessage.INVALID_MOVE_COMMAND.getMessage()); - } - Position source = parsePosition(parts.get(SOURCE_POSITION_INDEX)); - Position target = parsePosition(parts.get(TARGET_POSITION_INDEX)); - return new MoveCommand(source, target); - }); - commandMap.put(STATUS_COMMAND, parts -> new StatusCommand()); - } - - public CommandLauncher createCommand(String inputCommand) { - List commandParts = List.of(inputCommand.split(" ")); - String command = commandParts.get(COMMAND_INDEX); - - Function, CommandLauncher> commandCreator = commandMap.get(command); - if (commandCreator == null) { - throw new IllegalArgumentException(ErrorMessage.INVALID_COMMAND.getMessage()); - } - return commandCreator.apply(commandParts); - } - - private static Position parsePosition(String position) { - int file = position.charAt(0) - 'a' + 1; - int rank = position.charAt(1) - '0'; - return new Position(file, rank); // 생성자에 1~8 유효성 검사가 있다 - } -} diff --git a/src/main/java/chess/controller/command/commands/CommandLauncher.java b/src/main/java/chess/controller/command/commands/CommandLauncher.java deleted file mode 100644 index 0b055570d1..0000000000 --- a/src/main/java/chess/controller/command/commands/CommandLauncher.java +++ /dev/null @@ -1,9 +0,0 @@ -package chess.controller.command.commands; - -import chess.controller.ChessController; - -public interface CommandLauncher { - void execute(ChessController controller); - boolean validateInitialCommandType(); - boolean validateStatusCommandType(); -} diff --git a/src/main/java/chess/controller/command/commands/ContinueCommand.java b/src/main/java/chess/controller/command/commands/ContinueCommand.java new file mode 100644 index 0000000000..15d0347e22 --- /dev/null +++ b/src/main/java/chess/controller/command/commands/ContinueCommand.java @@ -0,0 +1,23 @@ +package chess.controller.command.commands; + +import chess.domain.game.ChessGame; +import chess.service.ChessGameService; +import chess.view.OutputView; +import java.sql.SQLException; + +public class ContinueCommand implements Command { + + @Override + public ChessGame initializeChessGame(final ChessGameService chessGameService) + throws SQLException { + ChessGame chessGame = chessGameService.findChessGame(); + if (chessGame == null) { + OutputView.printNoExistsRunningGameMessage(); + } + OutputView.printContinueMessage(); + return chessGame; + } + + @Override + public void execute(ChessGameService chessGameService) {} +} diff --git a/src/main/java/chess/controller/command/commands/EndCommand.java b/src/main/java/chess/controller/command/commands/EndCommand.java index 1d81d9e2ad..e2e2da58af 100644 --- a/src/main/java/chess/controller/command/commands/EndCommand.java +++ b/src/main/java/chess/controller/command/commands/EndCommand.java @@ -1,21 +1,23 @@ package chess.controller.command.commands; -import chess.controller.ChessController; +import chess.domain.game.ChessGame; +import chess.service.ChessGameService; -public class EndCommand implements CommandLauncher { +public class EndCommand implements Command { - @Override - public void execute(ChessController controller) { - // end + private final ChessGame chessGame; + + public EndCommand(ChessGame chessGame) { + this.chessGame = chessGame; } @Override - public boolean validateInitialCommandType() { - return true; + public void execute(final ChessGameService chessGameService) { + chessGame.end(); } @Override - public boolean validateStatusCommandType() { - return false; + public ChessGame initializeChessGame(final ChessGameService chessGameService) { + return null; } } diff --git a/src/main/java/chess/controller/command/commands/MoveCommand.java b/src/main/java/chess/controller/command/commands/MoveCommand.java index 9927024e5a..2c45f731b9 100644 --- a/src/main/java/chess/controller/command/commands/MoveCommand.java +++ b/src/main/java/chess/controller/command/commands/MoveCommand.java @@ -1,30 +1,51 @@ package chess.controller.command.commands; -import chess.controller.ChessController; +import chess.domain.game.ChessGame; +import chess.domain.game.State; +import chess.domain.position.Color; import chess.domain.position.Position; +import chess.service.ChessGameService; +import chess.view.OutputView; +import java.util.List; -public class MoveCommand implements CommandLauncher { +public class MoveCommand implements Command { + private static final int SOURCE_POSITION_INDEX = 1; + private static final int TARGET_POSITION_INDEX = 2; + + private final ChessGame chessGame; private final Position source; private final Position target; - public MoveCommand(Position source, Position target) { - this.source = source; - this.target = target; + public MoveCommand(ChessGame chessGame, List commandParts) { + this.chessGame = chessGame; + this.source = parsePosition(commandParts.get(SOURCE_POSITION_INDEX)); + this.target = parsePosition(commandParts.get(TARGET_POSITION_INDEX)); } @Override - public void execute(ChessController controller) { - // move + public void execute(final ChessGameService chessGameService) { + chessGame.movePiece(source, target); + chessGameService.updatePiece(chessGame, source, target); + OutputView.printBoard(chessGame.getBoard().getMap()); + processIfKingCaptured(chessGame); } - @Override - public boolean validateInitialCommandType() { - return false; + private static Position parsePosition(String position) { + int file = position.charAt(0) - 'a' + 1; + int rank = position.charAt(1) - '0'; + return new Position(file, rank); + } + + private void processIfKingCaptured(final ChessGame chessGame) { + if (chessGame.getState().equals(State.CHECKMATE)) { + final Color winner = chessGame.getTurn(); + OutputView.printWinningColor(winner); + } } @Override - public boolean validateStatusCommandType() { - return false; + public ChessGame initializeChessGame(final ChessGameService chessGameService) { + return null; } } diff --git a/src/main/java/chess/controller/command/commands/NewCommand.java b/src/main/java/chess/controller/command/commands/NewCommand.java new file mode 100644 index 0000000000..8e68701ef1 --- /dev/null +++ b/src/main/java/chess/controller/command/commands/NewCommand.java @@ -0,0 +1,21 @@ +package chess.controller.command.commands; + +import chess.domain.game.ChessGame; +import chess.service.ChessGameService; +import chess.view.OutputView; + +public class NewCommand implements Command { + + public NewCommand() { + } + + @Override + public ChessGame initializeChessGame(final ChessGameService chessGameService) { + OutputView.printNewGameMessage(); + chessGameService.deleteChessGame(); + return chessGameService.initializeChessGame(); + } + + @Override + public void execute(ChessGameService chessGameService) {} +} diff --git a/src/main/java/chess/controller/command/commands/StartCommand.java b/src/main/java/chess/controller/command/commands/StartCommand.java index 0731a7883a..82509940a1 100644 --- a/src/main/java/chess/controller/command/commands/StartCommand.java +++ b/src/main/java/chess/controller/command/commands/StartCommand.java @@ -1,21 +1,25 @@ package chess.controller.command.commands; -import chess.controller.ChessController; +import chess.domain.game.ChessGame; +import chess.service.ChessGameService; +import chess.view.OutputView; -public class StartCommand implements CommandLauncher { +public class StartCommand implements Command { - @Override - public void execute(ChessController controller) { - // start + private final ChessGame chessGame; + + public StartCommand(ChessGame chessGame) { + this.chessGame = chessGame; } @Override - public boolean validateInitialCommandType() { - return true; + public void execute(final ChessGameService chessGameService) { + chessGame.start(); + OutputView.printBoard(chessGame.getBoard().getMap()); } @Override - public boolean validateStatusCommandType() { - return false; + public ChessGame initializeChessGame(final ChessGameService chessGameService) { + return null; } } diff --git a/src/main/java/chess/controller/command/commands/StatusCommand.java b/src/main/java/chess/controller/command/commands/StatusCommand.java index 2d1e998ca8..d0460e3e8b 100644 --- a/src/main/java/chess/controller/command/commands/StatusCommand.java +++ b/src/main/java/chess/controller/command/commands/StatusCommand.java @@ -1,21 +1,40 @@ package chess.controller.command.commands; -import chess.controller.ChessController; +import chess.domain.game.ChessGame; +import chess.domain.position.Color; +import chess.service.ChessGameService; +import chess.view.OutputView; -public class StatusCommand implements CommandLauncher { +public class StatusCommand implements Command { - @Override - public void execute(ChessController controller) { - // calculate + private final ChessGame chessGame; + + public StatusCommand(ChessGame chessGame) { + this.chessGame = chessGame; } @Override - public boolean validateInitialCommandType() { - return false; + public void execute(final ChessGameService chessGameService) { + final Double whiteScore = chessGame.calculateScore(Color.WHITE); + final Double blackScore = chessGame.calculateScore(Color.BLACK); + printScoreAndWinningColor(whiteScore, blackScore); + } + + private void printScoreAndWinningColor(Double whiteScore, Double blackScore) { + OutputView.printScore(whiteScore, blackScore); + if (whiteScore > blackScore) { + OutputView.printWinningColor(Color.WHITE); + } + if (whiteScore < blackScore) { + OutputView.printWinningColor(Color.BLACK); + } + if (whiteScore.equals(blackScore)) { + OutputView.printDraw(); + } } @Override - public boolean validateStatusCommandType() { - return true; + public ChessGame initializeChessGame(final ChessGameService chessGameService) { + return null; } } diff --git a/src/main/java/chess/service/ChessGameService.java b/src/main/java/chess/service/ChessGameService.java index a7bcf5baae..efdd0b7b1f 100644 --- a/src/main/java/chess/service/ChessGameService.java +++ b/src/main/java/chess/service/ChessGameService.java @@ -27,9 +27,6 @@ public ChessGameService(final ChessGameDao chessGameDao, final PieceDao pieceDao public ChessGame findChessGame() throws SQLException { final FindResponseDto findResponseDto = chessGameDao.findChessGameById(TEMPORAL_ID); - if (findResponseDto == null) { - return null; - } return new ChessGame(findResponseDto.getId(), new Board(pieceDao.putPiecesById(TEMPORAL_ID)), findResponseDto.getTurn()); } diff --git a/src/main/java/chess/view/InputView.java b/src/main/java/chess/view/InputView.java index 16dfa07552..8f4c11b44b 100644 --- a/src/main/java/chess/view/InputView.java +++ b/src/main/java/chess/view/InputView.java @@ -6,7 +6,18 @@ public class InputView { private static final Scanner scanner = new Scanner(System.in); - public String receiveCommand() { + public static String receiveInitialCommand() { + System.out.println("> 체스 게임을 시작합니다."); + System.out.println("> 이어하기 : continue"); + System.out.println("> 새로하기 : new"); + return scanner.nextLine(); + } + + public static String receiveCommand() { + System.out.println("> 게임 시작 : start"); + System.out.println("> 게임 종료 : end"); + System.out.println("> 게임 이동 : move source 위치 target 위치 - 예. move b2 b3"); + System.out.println("> 점수 출력 : status"); return scanner.nextLine(); } } diff --git a/src/main/java/chess/view/OutputView.java b/src/main/java/chess/view/OutputView.java index 2e129ea9bb..1804cc5585 100644 --- a/src/main/java/chess/view/OutputView.java +++ b/src/main/java/chess/view/OutputView.java @@ -17,20 +17,7 @@ public class OutputView { private static final int BOARD_SIZE = 8; private static final int INDEX_OFFSET = 1; - public void printInitialMessage() { - System.out.println("> 체스 게임을 시작합니다."); - System.out.println("> 이어하기 : continue"); - System.out.println("> 새로하기 : new"); - } - - public void printCommandMessage() { - System.out.println("> 게임 시작 : start"); - System.out.println("> 게임 종료 : end"); - System.out.println("> 게임 이동 : move source 위치 target 위치 - 예. move b2 b3"); - System.out.println("> 점수 출력 : status"); - } - - public void printBoard(final Map boardMap) { + public static void printBoard(final Map boardMap) { List> chessBoard = createEmptyBoard(); assignSymbols(boardMap, chessBoard); @@ -39,37 +26,38 @@ public void printBoard(final Map boardMap) { .forEach(System.out::println); } - public void printScore(final Double whiteScore, final Double blackScore) { + public static void printScore(final Double whiteScore, final Double blackScore) { System.out.println("White Score: " + whiteScore); System.out.println("Black Score: " + blackScore); } - public void printWinningColor(Color currentTurn) { - System.out.println("Winning Color: " + currentTurn); + public static void printWinningColor(Color winningColor) { + System.out.println("Winning Color: " + winningColor); } - public void printDraw() { + public static void printDraw() { System.out.println("Draw"); } - public void printErrorMessage(final Exception e) { + public static void printErrorMessage(final Exception e) { System.out.println(e.getMessage()); System.out.print(System.lineSeparator()); } - public void printNewGameMessage() { + public static void printNewGameMessage() { System.out.println("새로운 게임을 시작합니다."); } - public void printContinueMessage() { + public static void printContinueMessage() { System.out.println("진행 중인 게임을 이어합니다."); } - public void printNoExistsRunningGameMessage() { - System.out.println("진행 중인 게임이 없어 이어할 수 없습니다."); + public static void printNoExistsRunningGameMessage() { + System.out.println("진행 중인 게임이 없습니다."); } - private void assignSymbols(final Map boardMap, final List> chessBoard) { + private static void assignSymbols(final Map boardMap, + final List> chessBoard) { for (final Map.Entry positionPieceEntry : boardMap.entrySet()) { final Position position = positionPieceEntry.getKey(); final Piece piece = positionPieceEntry.getValue(); @@ -83,7 +71,7 @@ private void assignSymbols(final Map boardMap, final List> createEmptyBoard() { + private static List> createEmptyBoard() { return IntStream.range(0, BOARD_SIZE) .mapToObj(it -> new ArrayList<>(Collections.nCopies(BOARD_SIZE, Symbol.EMPTY.getSymbol()))) .collect(Collectors.toList()); From 7c6c78e798433e0430ebf0ea43971f48a6dce686 Mon Sep 17 00:00:00 2001 From: junseoplee Date: Tue, 30 Jul 2024 00:17:44 +0900 Subject: [PATCH 20/23] =?UTF-8?q?feat:=20UnsupportedOperationException=20?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EC=82=AC=EC=9A=A9=EB=90=98=EC=A7=80=20?= =?UTF-8?q?=EC=95=8A=EB=8A=94=20=EB=A9=94=EC=84=9C=EB=93=9C=20=EA=B4=80?= =?UTF-8?q?=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/controller/ChessController.java | 4 ++-- .../chess/controller/command/commands/ContinueCommand.java | 4 +++- .../java/chess/controller/command/commands/EndCommand.java | 2 +- .../java/chess/controller/command/commands/MoveCommand.java | 2 +- .../java/chess/controller/command/commands/NewCommand.java | 4 +++- .../java/chess/controller/command/commands/StartCommand.java | 2 +- .../java/chess/controller/command/commands/StatusCommand.java | 2 +- 7 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index fe1b9104fb..e1eed2419e 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -29,7 +29,7 @@ private void executeCommand(ChessGame chessGame) { try { Command command = CommandFactory.createCommand(chessGame, InputView.receiveCommand()); command.execute(chessGameService); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException | UnsupportedOperationException e) { OutputView.printErrorMessage(e); executeCommand(chessGame); } @@ -39,7 +39,7 @@ private ChessGame executeInitialCommandAndFetchChessGame() throws SQLException { try { Command command = CommandFactory.createInitialCommand(InputView.receiveInitialCommand()); return command.initializeChessGame(chessGameService); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException | UnsupportedOperationException e) { OutputView.printErrorMessage(e); return executeInitialCommandAndFetchChessGame(); } diff --git a/src/main/java/chess/controller/command/commands/ContinueCommand.java b/src/main/java/chess/controller/command/commands/ContinueCommand.java index 15d0347e22..4898c7692d 100644 --- a/src/main/java/chess/controller/command/commands/ContinueCommand.java +++ b/src/main/java/chess/controller/command/commands/ContinueCommand.java @@ -19,5 +19,7 @@ public ChessGame initializeChessGame(final ChessGameService chessGameService) } @Override - public void execute(ChessGameService chessGameService) {} + public void execute(ChessGameService chessGameService) { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/chess/controller/command/commands/EndCommand.java b/src/main/java/chess/controller/command/commands/EndCommand.java index e2e2da58af..51631f295b 100644 --- a/src/main/java/chess/controller/command/commands/EndCommand.java +++ b/src/main/java/chess/controller/command/commands/EndCommand.java @@ -18,6 +18,6 @@ public void execute(final ChessGameService chessGameService) { @Override public ChessGame initializeChessGame(final ChessGameService chessGameService) { - return null; + throw new UnsupportedOperationException(); } } diff --git a/src/main/java/chess/controller/command/commands/MoveCommand.java b/src/main/java/chess/controller/command/commands/MoveCommand.java index 2c45f731b9..a032331ed1 100644 --- a/src/main/java/chess/controller/command/commands/MoveCommand.java +++ b/src/main/java/chess/controller/command/commands/MoveCommand.java @@ -46,6 +46,6 @@ private void processIfKingCaptured(final ChessGame chessGame) { @Override public ChessGame initializeChessGame(final ChessGameService chessGameService) { - return null; + throw new UnsupportedOperationException(); } } diff --git a/src/main/java/chess/controller/command/commands/NewCommand.java b/src/main/java/chess/controller/command/commands/NewCommand.java index 8e68701ef1..737a0ecdf1 100644 --- a/src/main/java/chess/controller/command/commands/NewCommand.java +++ b/src/main/java/chess/controller/command/commands/NewCommand.java @@ -17,5 +17,7 @@ public ChessGame initializeChessGame(final ChessGameService chessGameService) { } @Override - public void execute(ChessGameService chessGameService) {} + public void execute(ChessGameService chessGameService) { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/chess/controller/command/commands/StartCommand.java b/src/main/java/chess/controller/command/commands/StartCommand.java index 82509940a1..82f50f486c 100644 --- a/src/main/java/chess/controller/command/commands/StartCommand.java +++ b/src/main/java/chess/controller/command/commands/StartCommand.java @@ -20,6 +20,6 @@ public void execute(final ChessGameService chessGameService) { @Override public ChessGame initializeChessGame(final ChessGameService chessGameService) { - return null; + throw new UnsupportedOperationException(); } } diff --git a/src/main/java/chess/controller/command/commands/StatusCommand.java b/src/main/java/chess/controller/command/commands/StatusCommand.java index d0460e3e8b..cfd210c777 100644 --- a/src/main/java/chess/controller/command/commands/StatusCommand.java +++ b/src/main/java/chess/controller/command/commands/StatusCommand.java @@ -35,6 +35,6 @@ private void printScoreAndWinningColor(Double whiteScore, Double blackScore) { @Override public ChessGame initializeChessGame(final ChessGameService chessGameService) { - return null; + throw new UnsupportedOperationException(); } } From 0ad0e6587c60ab100190aeb94123fcda8965b800 Mon Sep 17 00:00:00 2001 From: junseoplee Date: Tue, 30 Jul 2024 00:35:08 +0900 Subject: [PATCH 21/23] =?UTF-8?q?test:=20=ED=8F=B0=EC=9D=98=20=EA=B3=B5?= =?UTF-8?q?=EA=B2=A9=20=EC=9B=80=EC=A7=81=EC=9E=84=EC=9D=84=20=EA=B2=80?= =?UTF-8?q?=EC=A6=9D=ED=95=98=EB=8A=94=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chess/domain/piece/pieces/PawnTest.java | 45 +++++++++---------- 1 file changed, 21 insertions(+), 24 deletions(-) diff --git a/src/test/java/chess/domain/piece/pieces/PawnTest.java b/src/test/java/chess/domain/piece/pieces/PawnTest.java index db881ae031..24a7149f08 100644 --- a/src/test/java/chess/domain/piece/pieces/PawnTest.java +++ b/src/test/java/chess/domain/piece/pieces/PawnTest.java @@ -76,30 +76,6 @@ class PawnTest { to); } - @ParameterizedTest - @CsvSource({ - "2, 2, 3, 3, WHITE", - "2, 2, 1, 3, WHITE", - "2, 7, 3, 6, BLACK", - "2, 7, 1, 6, BLACK" - }) - @DisplayName("폰은_대각선으로_한_칸_움직여_적을_공격할_수_있다") - void 폰은_대각선으로_한_칸_움직여_적을_공격할_수_있다(int fromFile, int fromRank, int toFile, int toRank, Color color) { - // given - Pawn pawn = new Pawn(color); - Position from = new Position(fromFile, fromRank); - Position to = new Position(toFile, toRank); - Map board = BoardFactory.createInitialBoard().getMap(); - - // when - Path path = pawn.findPath(from, to, board); - - // then - assertThat(path) - .extracting("positions", InstanceOfAssertFactories.list(Position.class)) - .containsExactly(to); - } - @Test @DisplayName("폰이_뒤로_움직인다면_예외_처리한다") void 폰이_뒤로_움직인다면_예외_처리한다() { @@ -129,4 +105,25 @@ class PawnTest { .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(ErrorMessage.INVALID_DIRECTION.getMessage()); } + + @ParameterizedTest + @CsvSource({ + "2, 2, 3, 3, WHITE", + "2, 2, 1, 3, WHITE", + "2, 7, 3, 6, BLACK", + "2, 7, 1, 6, BLACK" + }) + @DisplayName("폰이_대각선으로_움직이려할_때_적이_없으면_예외_처리한다") + void 폰이_대각선으로_움직이려할_때_적이_없으면_예외_처리한다(int fromFile, int fromRank, int toFile, int toRank, Color color) { + // given + Pawn pawn = new Pawn(color); + Position from = new Position(fromFile, fromRank); + Position to = new Position(toFile, toRank); + Map board = BoardFactory.createInitialBoard().getMap(); + + // when & then + assertThatThrownBy(() -> pawn.findPath(from, to, board)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(ErrorMessage.INVALID_DIRECTION.getMessage()); + } } From 3ce712df52d92401d5d5d1792f8f64873777cef9 Mon Sep 17 00:00:00 2001 From: junseoplee Date: Tue, 30 Jul 2024 03:09:43 +0900 Subject: [PATCH 22/23] =?UTF-8?q?fix:=20=EB=B3=80=EC=88=98=20=EC=9D=B4?= =?UTF-8?q?=EB=A6=84=EC=9D=84=20=EB=AA=85=ED=99=95=ED=95=98=EA=B2=8C=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/service/ChessGameService.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/chess/service/ChessGameService.java b/src/main/java/chess/service/ChessGameService.java index efdd0b7b1f..7504fca025 100644 --- a/src/main/java/chess/service/ChessGameService.java +++ b/src/main/java/chess/service/ChessGameService.java @@ -43,12 +43,12 @@ public ChessGame initializeChessGame() { return chessGame; } - public void updatePiece(final ChessGame chessGame, final Position sourcePosition, final Position targetPosition) { - final Piece piece = chessGame.getBoard().getPiece(targetPosition); + public void updatePiece(final ChessGame chessGame, final Position fromPosition, final Position toPosition) { + final Piece piece = chessGame.getBoard().getPiece(toPosition); - pieceDao.delete(chessGame.getId(), targetPosition); - pieceDao.insert(chessGame.getId(), targetPosition, piece); - pieceDao.delete(chessGame.getId(), sourcePosition); + pieceDao.delete(chessGame.getId(), toPosition); + pieceDao.insert(chessGame.getId(), toPosition, piece); + pieceDao.delete(chessGame.getId(), fromPosition); chessGameDao.updateTurn(chessGame.getId(), chessGame.getTurn()); } From d5483e46060071d323402ea3af7f0419d1f9f323 Mon Sep 17 00:00:00 2001 From: junseoplee Date: Tue, 30 Jul 2024 03:14:39 +0900 Subject: [PATCH 23/23] =?UTF-8?q?fix:=20=EC=83=81=ED=83=9C=EB=A5=BC=20?= =?UTF-8?q?=EB=8D=94=20=EB=AA=85=ED=99=95=ED=95=98=EA=B2=8C=20=EB=82=98?= =?UTF-8?q?=ED=83=80=EB=82=BC=20=EC=88=98=20=EC=9E=88=EB=8A=94=20=EC=9D=B4?= =?UTF-8?q?=EB=A6=84=EC=9C=BC=EB=A1=9C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/chess/controller/command/commands/MoveCommand.java | 2 +- src/main/java/chess/domain/game/ChessGame.java | 6 +++--- src/main/java/chess/domain/game/State.java | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/chess/controller/command/commands/MoveCommand.java b/src/main/java/chess/controller/command/commands/MoveCommand.java index a032331ed1..bbcf6bcf28 100644 --- a/src/main/java/chess/controller/command/commands/MoveCommand.java +++ b/src/main/java/chess/controller/command/commands/MoveCommand.java @@ -38,7 +38,7 @@ private static Position parsePosition(String position) { } private void processIfKingCaptured(final ChessGame chessGame) { - if (chessGame.getState().equals(State.CHECKMATE)) { + if (chessGame.getState().equals(State.KING_IS_CAPTURED)) { final Color winner = chessGame.getTurn(); OutputView.printWinningColor(winner); } diff --git a/src/main/java/chess/domain/game/ChessGame.java b/src/main/java/chess/domain/game/ChessGame.java index 6010da0ced..54b3fdde59 100644 --- a/src/main/java/chess/domain/game/ChessGame.java +++ b/src/main/java/chess/domain/game/ChessGame.java @@ -32,8 +32,8 @@ public void end() { this.state = State.ENDED; } - public void checkmate() { - this.state = State.CHECKMATE; + public void kingIsCaptured() { + this.state = State.KING_IS_CAPTURED; } public void movePiece(Position source, Position target) { @@ -57,7 +57,7 @@ private void checkRunning() { private void checkKingCaptured(Piece capturedPiece) { if (capturedPiece != null && capturedPiece.pieceType() == PieceInfo.KING) { - checkmate(); + kingIsCaptured(); } } diff --git a/src/main/java/chess/domain/game/State.java b/src/main/java/chess/domain/game/State.java index a94e58f3ba..51b84149f0 100644 --- a/src/main/java/chess/domain/game/State.java +++ b/src/main/java/chess/domain/game/State.java @@ -4,5 +4,5 @@ public enum State { WAITING, RUNNING, ENDED, - CHECKMATE + KING_IS_CAPTURED }