From 67ceea26184ab0eede1b43e65f8fd5229a8693a3 Mon Sep 17 00:00:00 2001 From: giantim Date: Tue, 24 Mar 2020 14:06:17 +0900 Subject: [PATCH 01/29] =?UTF-8?q?doc:=20=EC=B2=B4=EC=8A=A4=201=EB=8B=A8?= =?UTF-8?q?=EA=B3=84=20=EA=B8=B0=EB=8A=A5=20=EC=9A=94=EA=B5=AC=20=EC=82=AC?= =?UTF-8?q?=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 | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 86b3c5f3245..ef5dd275132 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,10 @@ # java-chess 체스 게임 구현을 위한 저장소 + +## 기능 요구 사항 + +1단계 + - [ ] 명령어를 입력 받는다(start, end) + - [ ] (예외) start, end 외의 명령어가 입력된 경우 다시 명령어를 입력 받는다 + - [ ] start 를 입력 시 체스판을 초기화 한다 + - [ ] end 를 입력 시 게임을 종료한다 From eee6977c2b968fc70440d7c531c863fd0d051018 Mon Sep 17 00:00:00 2001 From: giantim Date: Tue, 24 Mar 2020 14:54:59 +0900 Subject: [PATCH 02/29] =?UTF-8?q?feat:=20=EC=9C=84=EC=B9=98=20=EA=B5=AC?= =?UTF-8?q?=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/Position.java | 43 +++++++++++++++++++++++++++ src/main/java/chess/Rank.java | 27 +++++++++++++++++ src/test/java/chess/FileTest.java | 15 ++++++++++ src/test/java/chess/PositionTest.java | 15 ++++++++++ src/test/java/chess/RankTest.java | 15 ++++++++++ 5 files changed, 115 insertions(+) create mode 100644 src/main/java/chess/Position.java create mode 100644 src/main/java/chess/Rank.java create mode 100644 src/test/java/chess/FileTest.java create mode 100644 src/test/java/chess/PositionTest.java create mode 100644 src/test/java/chess/RankTest.java diff --git a/src/main/java/chess/Position.java b/src/main/java/chess/Position.java new file mode 100644 index 00000000000..75e0c5505b8 --- /dev/null +++ b/src/main/java/chess/Position.java @@ -0,0 +1,43 @@ +package chess; + +import java.util.ArrayList; +import java.util.List; + +public class Position { + private static List positions; + + private final File file; + private final Rank rank; + + private Position(File file, Rank rank) { + this.file = file; + this.rank = rank; + } + + static { + positions = new ArrayList<>(); + for (File file : File.values()) { + addPosition(file); + } + } + + private static void addPosition(File file) { + for (Rank rank : Rank.values()) { + positions.add(new Position(file, rank)); + } + } + + public static Position of(String position) { + File file = File.of(position.substring(0, 1)); + Rank rank = Rank.of(position.substring(1, 2)); + + return findPosition(file, rank); + } + + private static Position findPosition(File file, Rank rank) { + return positions.stream() + .filter(p -> p.file.equals(file) && p.rank.equals(rank)) + .findFirst() + .orElseThrow(AssertionError::new); + } +} diff --git a/src/main/java/chess/Rank.java b/src/main/java/chess/Rank.java new file mode 100644 index 00000000000..399c99c6938 --- /dev/null +++ b/src/main/java/chess/Rank.java @@ -0,0 +1,27 @@ +package chess; + +import java.util.Arrays; + +public enum Rank { + EIGHT(8), + SEVEN(7), + SIX(6), + FIVE(5), + FOUR(4), + THREE(3), + TWO(2), + ONE(1); + + private int rank; + + Rank(int rank) { + this.rank = rank; + } + + public static Rank of(String rank) { + return Arrays.stream(values()) + .filter(pv -> pv.rank == Integer.parseInt(rank)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("잘못된 y 좌표값을 입력하였습니다.")); + } +} diff --git a/src/test/java/chess/FileTest.java b/src/test/java/chess/FileTest.java new file mode 100644 index 00000000000..2b8c66c2929 --- /dev/null +++ b/src/test/java/chess/FileTest.java @@ -0,0 +1,15 @@ +package chess; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class FileTest { + @DisplayName("잘못된 x 좌표값이 들어왔을 때 예외 출력") + @Test + void ofTest() { + Assertions.assertThatThrownBy(() -> { + File.of("i"); + }).isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file diff --git a/src/test/java/chess/PositionTest.java b/src/test/java/chess/PositionTest.java new file mode 100644 index 00000000000..369d0f94814 --- /dev/null +++ b/src/test/java/chess/PositionTest.java @@ -0,0 +1,15 @@ +package chess; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class PositionTest { + @DisplayName("입력한 값으로 position 변경하는 기능") + @Test + void moveTest() { + Position position = Position.of("b2"); + + Assertions.assertThat(position).isEqualTo(Position.of("b2")); + } +} diff --git a/src/test/java/chess/RankTest.java b/src/test/java/chess/RankTest.java new file mode 100644 index 00000000000..3a6933b9a59 --- /dev/null +++ b/src/test/java/chess/RankTest.java @@ -0,0 +1,15 @@ +package chess; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class RankTest { + @DisplayName("잘못된 y 좌표 입력값에 대해 예외 처리 테스트") + @Test + void ofTest() { + Assertions.assertThatThrownBy(() -> { + Rank.of("9"); + }).isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file From a49d949709325b59bac56eabaff4ba238bea0981 Mon Sep 17 00:00:00 2001 From: giantim Date: Tue, 24 Mar 2020 14:56:16 +0900 Subject: [PATCH 03/29] =?UTF-8?q?feat:=20=EA=B0=80=EB=A1=9C=20=EC=B6=95=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/File.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/main/java/chess/File.java diff --git a/src/main/java/chess/File.java b/src/main/java/chess/File.java new file mode 100644 index 00000000000..a8460811fe2 --- /dev/null +++ b/src/main/java/chess/File.java @@ -0,0 +1,14 @@ +package chess; + +import java.util.Arrays; + +public enum File { + A, B, C, D, E, F, G, H; + + public static File of(String file) { + return Arrays.stream(values()) + .filter(ph -> ph.name().equals(file.toUpperCase())) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("잘못된 x 좌표값을 입력하였습니다.")); + } +} From 16267b56ea1012cbb31ae3c0db3139559c1e0123 Mon Sep 17 00:00:00 2001 From: giantim Date: Wed, 25 Mar 2020 13:43:26 +0900 Subject: [PATCH 04/29] =?UTF-8?q?feat:=20=EB=B3=B4=EB=93=9C=ED=8C=90=20?= =?UTF-8?q?=EC=B4=88=EA=B8=B0=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/ChessApplication.java | 10 ++++++ src/main/java/chess/controller/BoardDto.java | 16 ++++++++++ .../chess/controller/ChessController.java | 17 ++++++++++ .../java/chess/controller/PositionDto.java | 16 ++++++++++ src/main/java/chess/domain/board/Board.java | 25 +++++++++++++++ .../chess/domain/board/BoardInitializer.java | 32 +++++++++++++++++++ .../domain/initialize/BishopInitializer.java | 19 +++++++++++ .../domain/initialize/InitializeStrategy.java | 10 ++++++ .../domain/initialize/KingInitializer.java | 17 ++++++++++ .../domain/initialize/KnightInitializer.java | 19 +++++++++++ .../domain/initialize/PawnInitializer.java | 31 ++++++++++++++++++ .../domain/initialize/QueenInitializer.java | 17 ++++++++++ .../domain/initialize/RookInitializer.java | 19 +++++++++++ .../java/chess/domain/piece/PieceType.java | 22 +++++++++++++ .../chess/{ => domain/position}/File.java | 19 +++++++++-- .../chess/{ => domain/position}/Position.java | 22 ++++++++++--- .../chess/{ => domain/position}/Rank.java | 2 +- .../java/chess/view/ConsoleOutputView.java | 24 ++++++++++++++ src/main/java/chess/view/OutputView.java | 8 +++++ .../chess/{ => domain/position}/FileTest.java | 2 +- .../{ => domain/position}/PositionTest.java | 2 +- .../chess/{ => domain/position}/RankTest.java | 2 +- 22 files changed, 339 insertions(+), 12 deletions(-) create mode 100644 src/main/java/chess/ChessApplication.java create mode 100644 src/main/java/chess/controller/BoardDto.java create mode 100644 src/main/java/chess/controller/ChessController.java create mode 100644 src/main/java/chess/controller/PositionDto.java create mode 100644 src/main/java/chess/domain/board/Board.java create mode 100644 src/main/java/chess/domain/board/BoardInitializer.java create mode 100644 src/main/java/chess/domain/initialize/BishopInitializer.java create mode 100644 src/main/java/chess/domain/initialize/InitializeStrategy.java create mode 100644 src/main/java/chess/domain/initialize/KingInitializer.java create mode 100644 src/main/java/chess/domain/initialize/KnightInitializer.java create mode 100644 src/main/java/chess/domain/initialize/PawnInitializer.java create mode 100644 src/main/java/chess/domain/initialize/QueenInitializer.java create mode 100644 src/main/java/chess/domain/initialize/RookInitializer.java create mode 100644 src/main/java/chess/domain/piece/PieceType.java rename src/main/java/chess/{ => domain/position}/File.java (50%) rename src/main/java/chess/{ => domain/position}/Position.java (70%) rename src/main/java/chess/{ => domain/position}/Rank.java (94%) create mode 100644 src/main/java/chess/view/ConsoleOutputView.java create mode 100644 src/main/java/chess/view/OutputView.java rename src/test/java/chess/{ => domain/position}/FileTest.java (92%) rename src/test/java/chess/{ => domain/position}/PositionTest.java (92%) rename src/test/java/chess/{ => domain/position}/RankTest.java (92%) diff --git a/src/main/java/chess/ChessApplication.java b/src/main/java/chess/ChessApplication.java new file mode 100644 index 00000000000..f70d30b2b5f --- /dev/null +++ b/src/main/java/chess/ChessApplication.java @@ -0,0 +1,10 @@ +package chess; + +import chess.controller.ChessController; + +public class ChessApplication { + + public static void main(String[] args) { + ChessController.run(); + } +} \ No newline at end of file diff --git a/src/main/java/chess/controller/BoardDto.java b/src/main/java/chess/controller/BoardDto.java new file mode 100644 index 00000000000..e8b0aa88b43 --- /dev/null +++ b/src/main/java/chess/controller/BoardDto.java @@ -0,0 +1,16 @@ +package chess.controller; + +import java.util.Map; + +public class BoardDto { + + private Map board; + + public BoardDto(Map board) { + this.board = board; + } + + public Map get() { + return board; + } +} diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java new file mode 100644 index 00000000000..4dd09542914 --- /dev/null +++ b/src/main/java/chess/controller/ChessController.java @@ -0,0 +1,17 @@ +package chess.controller; + +import chess.domain.board.Board; +import chess.domain.position.Position; +import chess.view.ConsoleOutputView; +import chess.view.OutputView; + +public class ChessController { + private static OutputView outputView = new ConsoleOutputView(); + + public static void run() { + Board board = new Board(); + BoardDto boardDto = new BoardDto(board.get()); + PositionDto positionDto = new PositionDto(Position.getPositions()); + outputView.printBoard(positionDto.getPositions(), boardDto.get()); + } +} diff --git a/src/main/java/chess/controller/PositionDto.java b/src/main/java/chess/controller/PositionDto.java new file mode 100644 index 00000000000..8af6b20c9a3 --- /dev/null +++ b/src/main/java/chess/controller/PositionDto.java @@ -0,0 +1,16 @@ +package chess.controller; + +import java.util.List; + +public class PositionDto { + + private final List positions; + + public PositionDto(List positions) { + this.positions = positions; + } + + public List getPositions() { + return positions; + } +} diff --git a/src/main/java/chess/domain/board/Board.java b/src/main/java/chess/domain/board/Board.java new file mode 100644 index 00000000000..b49da019fdd --- /dev/null +++ b/src/main/java/chess/domain/board/Board.java @@ -0,0 +1,25 @@ +package chess.domain.board; + +import chess.domain.piece.PieceType; +import chess.domain.position.Position; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.stream.Collectors; + +public class Board { + private Map board; + + public Board() { + this.board = BoardInitializer.initializeAll(); + } + + public Map get() { + return board.entrySet() + .stream() + .collect(Collectors.toMap(entry -> entry.getKey().toString(), + entry -> entry.getValue().getName(), + (e1, e2) -> e1, LinkedHashMap::new)); + } +} diff --git a/src/main/java/chess/domain/board/BoardInitializer.java b/src/main/java/chess/domain/board/BoardInitializer.java new file mode 100644 index 00000000000..976240c07a3 --- /dev/null +++ b/src/main/java/chess/domain/board/BoardInitializer.java @@ -0,0 +1,32 @@ +package chess.domain.board; + +import chess.domain.initialize.*; +import chess.domain.piece.PieceType; +import chess.domain.position.Position; + +import java.util.*; + +public class BoardInitializer { + private static final List INITIALIZER; + + static { + INITIALIZER = new ArrayList<>(Arrays.asList( + new KingInitializer(), + new QueenInitializer(), + new RookInitializer(), + new KnightInitializer(), + new BishopInitializer(), + new PawnInitializer() + )); + } + + public static Map initializeAll() { + Map board = new HashMap<>(); + + for (InitializeStrategy strategy : INITIALIZER) { + board.putAll(strategy.initialize()); + } + + return board; + } +} diff --git a/src/main/java/chess/domain/initialize/BishopInitializer.java b/src/main/java/chess/domain/initialize/BishopInitializer.java new file mode 100644 index 00000000000..43dfa72531b --- /dev/null +++ b/src/main/java/chess/domain/initialize/BishopInitializer.java @@ -0,0 +1,19 @@ +package chess.domain.initialize; + +import chess.domain.piece.PieceType; +import chess.domain.position.Position; + +import java.util.*; + +public final class BishopInitializer implements InitializeStrategy { + @Override + public Map initialize() { + Map piece = new HashMap<>(); + piece.put(Position.of("c8"), PieceType.BISHOP); + piece.put(Position.of("c1"), PieceType.BISHOP); + piece.put(Position.of("f8"), PieceType.BISHOP); + piece.put(Position.of("f1"), PieceType.BISHOP); + + return Collections.unmodifiableMap(piece); + } +} \ No newline at end of file diff --git a/src/main/java/chess/domain/initialize/InitializeStrategy.java b/src/main/java/chess/domain/initialize/InitializeStrategy.java new file mode 100644 index 00000000000..038e1d2abe4 --- /dev/null +++ b/src/main/java/chess/domain/initialize/InitializeStrategy.java @@ -0,0 +1,10 @@ +package chess.domain.initialize; + +import chess.domain.piece.PieceType; +import chess.domain.position.Position; + +import java.util.Map; + +public interface InitializeStrategy { + Map initialize(); +} diff --git a/src/main/java/chess/domain/initialize/KingInitializer.java b/src/main/java/chess/domain/initialize/KingInitializer.java new file mode 100644 index 00000000000..c19217f1ba1 --- /dev/null +++ b/src/main/java/chess/domain/initialize/KingInitializer.java @@ -0,0 +1,17 @@ +package chess.domain.initialize; + +import chess.domain.piece.PieceType; +import chess.domain.position.Position; + +import java.util.*; + +public final class KingInitializer implements InitializeStrategy { + @Override + public Map initialize() { + Map piece = new HashMap<>(); + piece.put(Position.of("e8"), PieceType.KING); + piece.put(Position.of("e1"), PieceType.KING); + + return Collections.unmodifiableMap(piece); + } +} diff --git a/src/main/java/chess/domain/initialize/KnightInitializer.java b/src/main/java/chess/domain/initialize/KnightInitializer.java new file mode 100644 index 00000000000..bdbd3521439 --- /dev/null +++ b/src/main/java/chess/domain/initialize/KnightInitializer.java @@ -0,0 +1,19 @@ +package chess.domain.initialize; + +import chess.domain.piece.PieceType; +import chess.domain.position.Position; + +import java.util.*; + +public final class KnightInitializer implements InitializeStrategy { + @Override + public Map initialize() { + Map piece = new HashMap<>(); + piece.put(Position.of("b8"), PieceType.KNIGHT); + piece.put(Position.of("b1"), PieceType.KNIGHT); + piece.put(Position.of("g8"), PieceType.KNIGHT); + piece.put(Position.of("g1"), PieceType.KNIGHT); + + return Collections.unmodifiableMap(piece); + } +} \ No newline at end of file diff --git a/src/main/java/chess/domain/initialize/PawnInitializer.java b/src/main/java/chess/domain/initialize/PawnInitializer.java new file mode 100644 index 00000000000..1147aa8b3e7 --- /dev/null +++ b/src/main/java/chess/domain/initialize/PawnInitializer.java @@ -0,0 +1,31 @@ +package chess.domain.initialize; + +import chess.domain.piece.PieceType; +import chess.domain.position.Position; + +import java.util.*; + +public final class PawnInitializer implements InitializeStrategy { + @Override + public Map initialize() { + Map piece = new HashMap<>(); + piece.put(Position.of("a7"), PieceType.PAWN); + piece.put(Position.of("b7"), PieceType.PAWN); + piece.put(Position.of("c7"), PieceType.PAWN); + piece.put(Position.of("d7"), PieceType.PAWN); + piece.put(Position.of("e7"), PieceType.PAWN); + piece.put(Position.of("f7"), PieceType.PAWN); + piece.put(Position.of("g7"), PieceType.PAWN); + piece.put(Position.of("h7"), PieceType.PAWN); + piece.put(Position.of("a2"), PieceType.PAWN); + piece.put(Position.of("b2"), PieceType.PAWN); + piece.put(Position.of("c2"), PieceType.PAWN); + piece.put(Position.of("d2"), PieceType.PAWN); + piece.put(Position.of("e2"), PieceType.PAWN); + piece.put(Position.of("f2"), PieceType.PAWN); + piece.put(Position.of("g2"), PieceType.PAWN); + piece.put(Position.of("h2"), PieceType.PAWN); + + return Collections.unmodifiableMap(piece); + } +} diff --git a/src/main/java/chess/domain/initialize/QueenInitializer.java b/src/main/java/chess/domain/initialize/QueenInitializer.java new file mode 100644 index 00000000000..f19f1064278 --- /dev/null +++ b/src/main/java/chess/domain/initialize/QueenInitializer.java @@ -0,0 +1,17 @@ +package chess.domain.initialize; + +import chess.domain.piece.PieceType; +import chess.domain.position.Position; + +import java.util.*; + +public final class QueenInitializer implements InitializeStrategy { + @Override + public Map initialize() { + Map piece = new HashMap<>(); + piece.put(Position.of("d8"), PieceType.QUEEN); + piece.put(Position.of("d1"), PieceType.QUEEN); + + return Collections.unmodifiableMap(piece); + } +} \ No newline at end of file diff --git a/src/main/java/chess/domain/initialize/RookInitializer.java b/src/main/java/chess/domain/initialize/RookInitializer.java new file mode 100644 index 00000000000..5be7f5240b0 --- /dev/null +++ b/src/main/java/chess/domain/initialize/RookInitializer.java @@ -0,0 +1,19 @@ +package chess.domain.initialize; + +import chess.domain.piece.PieceType; +import chess.domain.position.Position; + +import java.util.*; + +public final class RookInitializer implements InitializeStrategy { + @Override + public Map initialize() { + Map piece = new HashMap<>(); + piece.put(Position.of("a8"), PieceType.ROOK); + piece.put(Position.of("a1"), PieceType.ROOK); + piece.put(Position.of("h8"), PieceType.ROOK); + piece.put(Position.of("h1"), PieceType.ROOK); + + return Collections.unmodifiableMap(piece); + } +} \ No newline at end of file diff --git a/src/main/java/chess/domain/piece/PieceType.java b/src/main/java/chess/domain/piece/PieceType.java new file mode 100644 index 00000000000..5186eec729d --- /dev/null +++ b/src/main/java/chess/domain/piece/PieceType.java @@ -0,0 +1,22 @@ +package chess.domain.piece; + +public enum PieceType { + KING("k", 0), + QUEEN("q", 9), + ROOK("r", 5), + BISHOP("b", 3), + KNIGHT("n", 2.5), + PAWN("p", 1); + + private String name; + private double score; + + PieceType(String name, double score) { + this.name = name; + this.score = score; + } + + public String getName() { + return name; + } +} diff --git a/src/main/java/chess/File.java b/src/main/java/chess/domain/position/File.java similarity index 50% rename from src/main/java/chess/File.java rename to src/main/java/chess/domain/position/File.java index a8460811fe2..81ff817ee66 100644 --- a/src/main/java/chess/File.java +++ b/src/main/java/chess/domain/position/File.java @@ -1,13 +1,26 @@ -package chess; +package chess.domain.position; import java.util.Arrays; public enum File { - A, B, C, D, E, F, G, H; + A("a"), + B("b"), + C("c"), + D("d"), + E("e"), + F("f"), + G("g"), + H("h"); + + private String name; + + File(String name) { + this.name = name; + } public static File of(String file) { return Arrays.stream(values()) - .filter(ph -> ph.name().equals(file.toUpperCase())) + .filter(ph -> ph.name.equals(file.toLowerCase())) .findFirst() .orElseThrow(() -> new IllegalArgumentException("잘못된 x 좌표값을 입력하였습니다.")); } diff --git a/src/main/java/chess/Position.java b/src/main/java/chess/domain/position/Position.java similarity index 70% rename from src/main/java/chess/Position.java rename to src/main/java/chess/domain/position/Position.java index 75e0c5505b8..292ef06fed4 100644 --- a/src/main/java/chess/Position.java +++ b/src/main/java/chess/domain/position/Position.java @@ -1,7 +1,8 @@ -package chess; +package chess.domain.position; import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; public class Position { private static List positions; @@ -16,13 +17,13 @@ private Position(File file, Rank rank) { static { positions = new ArrayList<>(); - for (File file : File.values()) { - addPosition(file); + for (Rank rank : Rank.values()) { + addPosition(rank); } } - private static void addPosition(File file) { - for (Rank rank : Rank.values()) { + private static void addPosition(Rank rank) { + for (File file : File.values()) { positions.add(new Position(file, rank)); } } @@ -40,4 +41,15 @@ private static Position findPosition(File file, Rank rank) { .findFirst() .orElseThrow(AssertionError::new); } + + public static List getPositions() { + return positions.stream() + .map(Position::toString) + .collect(Collectors.toList()); + } + + @Override + public String toString() { + return file.name() + rank.name(); + } } diff --git a/src/main/java/chess/Rank.java b/src/main/java/chess/domain/position/Rank.java similarity index 94% rename from src/main/java/chess/Rank.java rename to src/main/java/chess/domain/position/Rank.java index 399c99c6938..7b56f82e412 100644 --- a/src/main/java/chess/Rank.java +++ b/src/main/java/chess/domain/position/Rank.java @@ -1,4 +1,4 @@ -package chess; +package chess.domain.position; import java.util.Arrays; diff --git a/src/main/java/chess/view/ConsoleOutputView.java b/src/main/java/chess/view/ConsoleOutputView.java new file mode 100644 index 00000000000..9ed1c865145 --- /dev/null +++ b/src/main/java/chess/view/ConsoleOutputView.java @@ -0,0 +1,24 @@ +package chess.view; + +import java.util.List; +import java.util.Map; + +public class ConsoleOutputView implements OutputView { + @Override + public void printBoard(List positions, Map board) { + for (int i = 1; i <= positions.size(); i++) { + String piece = board.get(positions.get(i - 1)); + System.out.print(printPiece(piece)); + if (i % 8 == 0) { + System.out.println(); + } + } + } + + private String printPiece(String piece) { + if (piece == null) { + return "."; + } + return piece; + } +} diff --git a/src/main/java/chess/view/OutputView.java b/src/main/java/chess/view/OutputView.java new file mode 100644 index 00000000000..578a232713f --- /dev/null +++ b/src/main/java/chess/view/OutputView.java @@ -0,0 +1,8 @@ +package chess.view; + +import java.util.List; +import java.util.Map; + +public interface OutputView { + void printBoard(List positions, Map board); +} diff --git a/src/test/java/chess/FileTest.java b/src/test/java/chess/domain/position/FileTest.java similarity index 92% rename from src/test/java/chess/FileTest.java rename to src/test/java/chess/domain/position/FileTest.java index 2b8c66c2929..d5892185db6 100644 --- a/src/test/java/chess/FileTest.java +++ b/src/test/java/chess/domain/position/FileTest.java @@ -1,4 +1,4 @@ -package chess; +package chess.domain.position; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.DisplayName; diff --git a/src/test/java/chess/PositionTest.java b/src/test/java/chess/domain/position/PositionTest.java similarity index 92% rename from src/test/java/chess/PositionTest.java rename to src/test/java/chess/domain/position/PositionTest.java index 369d0f94814..890c88097cf 100644 --- a/src/test/java/chess/PositionTest.java +++ b/src/test/java/chess/domain/position/PositionTest.java @@ -1,4 +1,4 @@ -package chess; +package chess.domain.position; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.DisplayName; diff --git a/src/test/java/chess/RankTest.java b/src/test/java/chess/domain/position/RankTest.java similarity index 92% rename from src/test/java/chess/RankTest.java rename to src/test/java/chess/domain/position/RankTest.java index 3a6933b9a59..485e04d7753 100644 --- a/src/test/java/chess/RankTest.java +++ b/src/test/java/chess/domain/position/RankTest.java @@ -1,4 +1,4 @@ -package chess; +package chess.domain.position; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.DisplayName; From 9d82c7269ce1d19ef3f2da5b8ca349d5be8183e3 Mon Sep 17 00:00:00 2001 From: giantim Date: Wed, 25 Mar 2020 15:06:14 +0900 Subject: [PATCH 05/29] =?UTF-8?q?feat:=20=EC=B2=B4=EC=8A=A4=20=EA=B2=8C?= =?UTF-8?q?=EC=9E=84=EC=9D=84=20=EC=8B=9C=EC=9E=91=ED=95=98=EB=8A=94=20?= =?UTF-8?q?=EB=AA=85=EB=A0=B9=EC=96=B4=20=EC=9E=85=EB=A0=A5=20refactor:=20?= =?UTF-8?q?final=20=ED=82=A4=EC=9B=8C=EB=93=9C=20=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/controller/BoardDto.java | 16 ------- .../chess/controller/ChessController.java | 15 ++++++- .../java/chess/controller/dto/BoardDto.java | 16 +++++++ .../controller/{ => dto}/PositionDto.java | 8 ++-- src/main/java/chess/domain/board/Board.java | 13 +++--- .../chess/domain/board/BoardInitializer.java | 8 ++-- .../domain/initialize/BishopInitializer.java | 20 +++++---- .../domain/initialize/InitializeStrategy.java | 4 +- .../domain/initialize/KingInitializer.java | 16 ++++--- .../domain/initialize/KnightInitializer.java | 20 +++++---- .../domain/initialize/PawnInitializer.java | 45 ++++++++++--------- .../domain/initialize/QueenInitializer.java | 16 ++++--- .../domain/initialize/RookInitializer.java | 20 +++++---- src/main/java/chess/domain/piece/Piece.java | 15 +++++++ .../java/chess/domain/piece/PieceType.java | 12 ++--- src/main/java/chess/domain/piece/Team.java | 18 ++++++++ src/main/java/chess/domain/position/File.java | 2 +- .../java/chess/domain/position/Position.java | 8 ++-- src/main/java/chess/domain/position/Rank.java | 2 +- .../java/chess/view/ConsoleInputView.java | 36 +++++++++++++++ .../java/chess/view/ConsoleOutputView.java | 17 ++++--- src/main/java/chess/view/InputView.java | 5 +++ 22 files changed, 226 insertions(+), 106 deletions(-) delete mode 100644 src/main/java/chess/controller/BoardDto.java create mode 100644 src/main/java/chess/controller/dto/BoardDto.java rename src/main/java/chess/controller/{ => dto}/PositionDto.java (52%) create mode 100644 src/main/java/chess/domain/piece/Piece.java create mode 100644 src/main/java/chess/domain/piece/Team.java create mode 100644 src/main/java/chess/view/ConsoleInputView.java create mode 100644 src/main/java/chess/view/InputView.java diff --git a/src/main/java/chess/controller/BoardDto.java b/src/main/java/chess/controller/BoardDto.java deleted file mode 100644 index e8b0aa88b43..00000000000 --- a/src/main/java/chess/controller/BoardDto.java +++ /dev/null @@ -1,16 +0,0 @@ -package chess.controller; - -import java.util.Map; - -public class BoardDto { - - private Map board; - - public BoardDto(Map board) { - this.board = board; - } - - public Map get() { - return board; - } -} diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index 4dd09542914..d75a0b61b39 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -1,16 +1,27 @@ package chess.controller; +import chess.controller.dto.BoardDto; +import chess.controller.dto.PositionDto; import chess.domain.board.Board; import chess.domain.position.Position; +import chess.view.ConsoleInputView; import chess.view.ConsoleOutputView; +import chess.view.InputView; import chess.view.OutputView; public class ChessController { + private static InputView inputView = new ConsoleInputView(); private static OutputView outputView = new ConsoleOutputView(); public static void run() { - Board board = new Board(); - BoardDto boardDto = new BoardDto(board.get()); + if (inputView.askChessRun()) { + Board board = new Board(); + printInitialize(board); + } + } + + private static void printInitialize(Board board) { + BoardDto boardDto = new BoardDto(board.parse()); PositionDto positionDto = new PositionDto(Position.getPositions()); outputView.printBoard(positionDto.getPositions(), boardDto.get()); } diff --git a/src/main/java/chess/controller/dto/BoardDto.java b/src/main/java/chess/controller/dto/BoardDto.java new file mode 100644 index 00000000000..cbc17ea78b5 --- /dev/null +++ b/src/main/java/chess/controller/dto/BoardDto.java @@ -0,0 +1,16 @@ +package chess.controller.dto; + +import java.util.Collections; +import java.util.Map; + +public class BoardDto { + private final Map board; + + public BoardDto(final Map board) { + this.board = board; + } + + public Map get() { + return Collections.unmodifiableMap(this.board); + } +} diff --git a/src/main/java/chess/controller/PositionDto.java b/src/main/java/chess/controller/dto/PositionDto.java similarity index 52% rename from src/main/java/chess/controller/PositionDto.java rename to src/main/java/chess/controller/dto/PositionDto.java index 8af6b20c9a3..db5875990fe 100644 --- a/src/main/java/chess/controller/PositionDto.java +++ b/src/main/java/chess/controller/dto/PositionDto.java @@ -1,16 +1,16 @@ -package chess.controller; +package chess.controller.dto; +import java.util.Collections; import java.util.List; public class PositionDto { - private final List positions; - public PositionDto(List positions) { + public PositionDto(final List positions) { this.positions = positions; } public List getPositions() { - return positions; + return Collections.unmodifiableList(positions); } } diff --git a/src/main/java/chess/domain/board/Board.java b/src/main/java/chess/domain/board/Board.java index b49da019fdd..df7d71e2bf1 100644 --- a/src/main/java/chess/domain/board/Board.java +++ b/src/main/java/chess/domain/board/Board.java @@ -1,25 +1,26 @@ package chess.domain.board; -import chess.domain.piece.PieceType; +import chess.domain.piece.Piece; import chess.domain.position.Position; -import java.util.HashMap; +import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; public class Board { - private Map board; + private final Map board; public Board() { this.board = BoardInitializer.initializeAll(); } - public Map get() { - return board.entrySet() + public Map parse() { + Map parseResult = board.entrySet() .stream() .collect(Collectors.toMap(entry -> entry.getKey().toString(), - entry -> entry.getValue().getName(), + entry -> entry.getValue().toSymbol(), (e1, e2) -> e1, LinkedHashMap::new)); + return Collections.unmodifiableMap(parseResult); } } diff --git a/src/main/java/chess/domain/board/BoardInitializer.java b/src/main/java/chess/domain/board/BoardInitializer.java index 976240c07a3..573184ac6fd 100644 --- a/src/main/java/chess/domain/board/BoardInitializer.java +++ b/src/main/java/chess/domain/board/BoardInitializer.java @@ -1,7 +1,7 @@ package chess.domain.board; import chess.domain.initialize.*; -import chess.domain.piece.PieceType; +import chess.domain.piece.Piece; import chess.domain.position.Position; import java.util.*; @@ -20,13 +20,13 @@ public class BoardInitializer { )); } - public static Map initializeAll() { - Map board = new HashMap<>(); + public static Map initializeAll() { + Map board = new HashMap<>(); for (InitializeStrategy strategy : INITIALIZER) { board.putAll(strategy.initialize()); } - return board; + return Collections.unmodifiableMap(board); } } diff --git a/src/main/java/chess/domain/initialize/BishopInitializer.java b/src/main/java/chess/domain/initialize/BishopInitializer.java index 43dfa72531b..da628c0905d 100644 --- a/src/main/java/chess/domain/initialize/BishopInitializer.java +++ b/src/main/java/chess/domain/initialize/BishopInitializer.java @@ -1,19 +1,23 @@ package chess.domain.initialize; +import chess.domain.piece.Piece; import chess.domain.piece.PieceType; +import chess.domain.piece.Team; import chess.domain.position.Position; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; public final class BishopInitializer implements InitializeStrategy { @Override - public Map initialize() { - Map piece = new HashMap<>(); - piece.put(Position.of("c8"), PieceType.BISHOP); - piece.put(Position.of("c1"), PieceType.BISHOP); - piece.put(Position.of("f8"), PieceType.BISHOP); - piece.put(Position.of("f1"), PieceType.BISHOP); + public Map initialize() { + Map pieces = new HashMap<>(); + pieces.put(Position.of("c8"), new Piece(PieceType.BISHOP, Team.BLACK)); + pieces.put(Position.of("c1"), new Piece(PieceType.BISHOP, Team.WHITE)); + pieces.put(Position.of("f8"), new Piece(PieceType.BISHOP, Team.BLACK)); + pieces.put(Position.of("f1"), new Piece(PieceType.BISHOP, Team.WHITE)); - return Collections.unmodifiableMap(piece); + return Collections.unmodifiableMap(pieces); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/initialize/InitializeStrategy.java b/src/main/java/chess/domain/initialize/InitializeStrategy.java index 038e1d2abe4..47fc1403522 100644 --- a/src/main/java/chess/domain/initialize/InitializeStrategy.java +++ b/src/main/java/chess/domain/initialize/InitializeStrategy.java @@ -1,10 +1,10 @@ package chess.domain.initialize; -import chess.domain.piece.PieceType; +import chess.domain.piece.Piece; import chess.domain.position.Position; import java.util.Map; public interface InitializeStrategy { - Map initialize(); + Map initialize(); } diff --git a/src/main/java/chess/domain/initialize/KingInitializer.java b/src/main/java/chess/domain/initialize/KingInitializer.java index c19217f1ba1..9ce672ddc12 100644 --- a/src/main/java/chess/domain/initialize/KingInitializer.java +++ b/src/main/java/chess/domain/initialize/KingInitializer.java @@ -1,17 +1,21 @@ package chess.domain.initialize; +import chess.domain.piece.Piece; import chess.domain.piece.PieceType; +import chess.domain.piece.Team; import chess.domain.position.Position; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; public final class KingInitializer implements InitializeStrategy { @Override - public Map initialize() { - Map piece = new HashMap<>(); - piece.put(Position.of("e8"), PieceType.KING); - piece.put(Position.of("e1"), PieceType.KING); + public Map initialize() { + Map pieces = new HashMap<>(); + pieces.put(Position.of("e8"), new Piece(PieceType.KING, Team.BLACK)); + pieces.put(Position.of("e1"), new Piece(PieceType.KING, Team.WHITE)); - return Collections.unmodifiableMap(piece); + return Collections.unmodifiableMap(pieces); } } diff --git a/src/main/java/chess/domain/initialize/KnightInitializer.java b/src/main/java/chess/domain/initialize/KnightInitializer.java index bdbd3521439..a8f3edfd4fb 100644 --- a/src/main/java/chess/domain/initialize/KnightInitializer.java +++ b/src/main/java/chess/domain/initialize/KnightInitializer.java @@ -1,19 +1,23 @@ package chess.domain.initialize; +import chess.domain.piece.Piece; import chess.domain.piece.PieceType; +import chess.domain.piece.Team; import chess.domain.position.Position; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; public final class KnightInitializer implements InitializeStrategy { @Override - public Map initialize() { - Map piece = new HashMap<>(); - piece.put(Position.of("b8"), PieceType.KNIGHT); - piece.put(Position.of("b1"), PieceType.KNIGHT); - piece.put(Position.of("g8"), PieceType.KNIGHT); - piece.put(Position.of("g1"), PieceType.KNIGHT); + public Map initialize() { + Map pieces = new HashMap<>(); + pieces.put(Position.of("b8"), new Piece(PieceType.KNIGHT, Team.BLACK)); + pieces.put(Position.of("b1"), new Piece(PieceType.KNIGHT, Team.WHITE)); + pieces.put(Position.of("g8"), new Piece(PieceType.KNIGHT, Team.BLACK)); + pieces.put(Position.of("g1"), new Piece(PieceType.KNIGHT, Team.WHITE)); - return Collections.unmodifiableMap(piece); + return Collections.unmodifiableMap(pieces); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/initialize/PawnInitializer.java b/src/main/java/chess/domain/initialize/PawnInitializer.java index 1147aa8b3e7..ced1279ba67 100644 --- a/src/main/java/chess/domain/initialize/PawnInitializer.java +++ b/src/main/java/chess/domain/initialize/PawnInitializer.java @@ -1,31 +1,36 @@ package chess.domain.initialize; +import chess.domain.piece.Piece; import chess.domain.piece.PieceType; +import chess.domain.piece.Team; import chess.domain.position.Position; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; public final class PawnInitializer implements InitializeStrategy { @Override - public Map initialize() { - Map piece = new HashMap<>(); - piece.put(Position.of("a7"), PieceType.PAWN); - piece.put(Position.of("b7"), PieceType.PAWN); - piece.put(Position.of("c7"), PieceType.PAWN); - piece.put(Position.of("d7"), PieceType.PAWN); - piece.put(Position.of("e7"), PieceType.PAWN); - piece.put(Position.of("f7"), PieceType.PAWN); - piece.put(Position.of("g7"), PieceType.PAWN); - piece.put(Position.of("h7"), PieceType.PAWN); - piece.put(Position.of("a2"), PieceType.PAWN); - piece.put(Position.of("b2"), PieceType.PAWN); - piece.put(Position.of("c2"), PieceType.PAWN); - piece.put(Position.of("d2"), PieceType.PAWN); - piece.put(Position.of("e2"), PieceType.PAWN); - piece.put(Position.of("f2"), PieceType.PAWN); - piece.put(Position.of("g2"), PieceType.PAWN); - piece.put(Position.of("h2"), PieceType.PAWN); + public Map initialize() { + Map pieces = new HashMap<>(); + pieces.put(Position.of("a7"), new Piece(PieceType.PAWN, Team.BLACK)); + pieces.put(Position.of("b7"), new Piece(PieceType.PAWN, Team.BLACK)); + pieces.put(Position.of("c7"), new Piece(PieceType.PAWN, Team.BLACK)); + pieces.put(Position.of("d7"), new Piece(PieceType.PAWN, Team.BLACK)); + pieces.put(Position.of("e7"), new Piece(PieceType.PAWN, Team.BLACK)); + pieces.put(Position.of("f7"), new Piece(PieceType.PAWN, Team.BLACK)); + pieces.put(Position.of("g7"), new Piece(PieceType.PAWN, Team.BLACK)); + pieces.put(Position.of("h7"), new Piece(PieceType.PAWN, Team.BLACK)); - return Collections.unmodifiableMap(piece); + pieces.put(Position.of("a2"), new Piece(PieceType.PAWN, Team.WHITE)); + pieces.put(Position.of("b2"), new Piece(PieceType.PAWN, Team.WHITE)); + pieces.put(Position.of("c2"), new Piece(PieceType.PAWN, Team.WHITE)); + pieces.put(Position.of("d2"), new Piece(PieceType.PAWN, Team.WHITE)); + pieces.put(Position.of("e2"), new Piece(PieceType.PAWN, Team.WHITE)); + pieces.put(Position.of("f2"), new Piece(PieceType.PAWN, Team.WHITE)); + pieces.put(Position.of("g2"), new Piece(PieceType.PAWN, Team.WHITE)); + pieces.put(Position.of("h2"), new Piece(PieceType.PAWN, Team.WHITE)); + + return Collections.unmodifiableMap(pieces); } } diff --git a/src/main/java/chess/domain/initialize/QueenInitializer.java b/src/main/java/chess/domain/initialize/QueenInitializer.java index f19f1064278..507f401250c 100644 --- a/src/main/java/chess/domain/initialize/QueenInitializer.java +++ b/src/main/java/chess/domain/initialize/QueenInitializer.java @@ -1,17 +1,21 @@ package chess.domain.initialize; +import chess.domain.piece.Piece; import chess.domain.piece.PieceType; +import chess.domain.piece.Team; import chess.domain.position.Position; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; public final class QueenInitializer implements InitializeStrategy { @Override - public Map initialize() { - Map piece = new HashMap<>(); - piece.put(Position.of("d8"), PieceType.QUEEN); - piece.put(Position.of("d1"), PieceType.QUEEN); + public Map initialize() { + Map pieces = new HashMap<>(); + pieces.put(Position.of("d8"), new Piece(PieceType.QUEEN, Team.BLACK)); + pieces.put(Position.of("d1"), new Piece(PieceType.QUEEN, Team.WHITE)); - return Collections.unmodifiableMap(piece); + return Collections.unmodifiableMap(pieces); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/initialize/RookInitializer.java b/src/main/java/chess/domain/initialize/RookInitializer.java index 5be7f5240b0..47fd77a442e 100644 --- a/src/main/java/chess/domain/initialize/RookInitializer.java +++ b/src/main/java/chess/domain/initialize/RookInitializer.java @@ -1,19 +1,23 @@ package chess.domain.initialize; +import chess.domain.piece.Piece; import chess.domain.piece.PieceType; +import chess.domain.piece.Team; import chess.domain.position.Position; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; public final class RookInitializer implements InitializeStrategy { @Override - public Map initialize() { - Map piece = new HashMap<>(); - piece.put(Position.of("a8"), PieceType.ROOK); - piece.put(Position.of("a1"), PieceType.ROOK); - piece.put(Position.of("h8"), PieceType.ROOK); - piece.put(Position.of("h1"), PieceType.ROOK); + public Map initialize() { + Map pieces = new HashMap<>(); + pieces.put(Position.of("a8"), new Piece(PieceType.ROOK, Team.BLACK)); + pieces.put(Position.of("a1"), new Piece(PieceType.ROOK, Team.WHITE)); + pieces.put(Position.of("h8"), new Piece(PieceType.ROOK, Team.BLACK)); + pieces.put(Position.of("h1"), new Piece(PieceType.ROOK, Team.WHITE)); - return Collections.unmodifiableMap(piece); + return Collections.unmodifiableMap(pieces); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/piece/Piece.java b/src/main/java/chess/domain/piece/Piece.java new file mode 100644 index 00000000000..68b661d453e --- /dev/null +++ b/src/main/java/chess/domain/piece/Piece.java @@ -0,0 +1,15 @@ +package chess.domain.piece; + +public class Piece { + private final PieceType pieceType; + private final Team team; + + public Piece(final PieceType pieceType, final Team team) { + this.pieceType = pieceType; + this.team = team; + } + + public String toSymbol() { + return this.team.convert(this.pieceType.getSymbol()); + } +} diff --git a/src/main/java/chess/domain/piece/PieceType.java b/src/main/java/chess/domain/piece/PieceType.java index 5186eec729d..cfe6e8a92cb 100644 --- a/src/main/java/chess/domain/piece/PieceType.java +++ b/src/main/java/chess/domain/piece/PieceType.java @@ -8,15 +8,15 @@ public enum PieceType { KNIGHT("n", 2.5), PAWN("p", 1); - private String name; - private double score; + private final String symbol; + private final double score; - PieceType(String name, double score) { - this.name = name; + PieceType(String symbol, double score) { + this.symbol = symbol; this.score = score; } - public String getName() { - return name; + public String getSymbol() { + return symbol; } } diff --git a/src/main/java/chess/domain/piece/Team.java b/src/main/java/chess/domain/piece/Team.java new file mode 100644 index 00000000000..ec97b6aa539 --- /dev/null +++ b/src/main/java/chess/domain/piece/Team.java @@ -0,0 +1,18 @@ +package chess.domain.piece; + +import java.util.function.Function; + +public enum Team { + BLACK(String::toUpperCase), + WHITE(String::toLowerCase); + + private final Function expression; + + Team(Function expression) { + this.expression = expression; + } + + public String convert(final String name) { + return this.expression.apply(name); + } +} diff --git a/src/main/java/chess/domain/position/File.java b/src/main/java/chess/domain/position/File.java index 81ff817ee66..d4212488217 100644 --- a/src/main/java/chess/domain/position/File.java +++ b/src/main/java/chess/domain/position/File.java @@ -12,7 +12,7 @@ public enum File { G("g"), H("h"); - private String name; + private final String name; File(String name) { this.name = name; diff --git a/src/main/java/chess/domain/position/Position.java b/src/main/java/chess/domain/position/Position.java index 292ef06fed4..0f51e44f09e 100644 --- a/src/main/java/chess/domain/position/Position.java +++ b/src/main/java/chess/domain/position/Position.java @@ -1,6 +1,7 @@ package chess.domain.position; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -10,7 +11,7 @@ public class Position { private final File file; private final Rank rank; - private Position(File file, Rank rank) { + private Position(final File file, final Rank rank) { this.file = file; this.rank = rank; } @@ -28,7 +29,7 @@ private static void addPosition(Rank rank) { } } - public static Position of(String position) { + public static Position of(final String position) { File file = File.of(position.substring(0, 1)); Rank rank = Rank.of(position.substring(1, 2)); @@ -43,9 +44,10 @@ private static Position findPosition(File file, Rank rank) { } public static List getPositions() { - return positions.stream() + List parseResult = positions.stream() .map(Position::toString) .collect(Collectors.toList()); + return Collections.unmodifiableList(parseResult); } @Override diff --git a/src/main/java/chess/domain/position/Rank.java b/src/main/java/chess/domain/position/Rank.java index 7b56f82e412..6d0c3c582eb 100644 --- a/src/main/java/chess/domain/position/Rank.java +++ b/src/main/java/chess/domain/position/Rank.java @@ -12,7 +12,7 @@ public enum Rank { TWO(2), ONE(1); - private int rank; + private final int rank; Rank(int rank) { this.rank = rank; diff --git a/src/main/java/chess/view/ConsoleInputView.java b/src/main/java/chess/view/ConsoleInputView.java new file mode 100644 index 00000000000..3daac277af9 --- /dev/null +++ b/src/main/java/chess/view/ConsoleInputView.java @@ -0,0 +1,36 @@ +package chess.view; + +import java.util.Scanner; + +public class ConsoleInputView implements InputView { + private static final Scanner SCANNER = new Scanner(System.in); + private static final String START_COMMAND = "start"; + private static final String END_COMMAND = "end"; + + @Override + public boolean askChessRun() { + try { + System.out.println("체스 게임을 시작합니다."); + System.out.println("게임 시작은 start, 종료는 end 명령어를 입력하세요."); + String input = SCANNER.nextLine(); + validateCommand(input); + return runFlag(input); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return askChessRun(); + } + } + + private void validateCommand(String input) { + if (!input.equals(START_COMMAND) && !input.equals(END_COMMAND)) { + throw new IllegalArgumentException("start 또는 end 를 입력해주세요."); + } + } + + private boolean runFlag(String input) { + if (input.equals(START_COMMAND)) { + return true; + } + return false; + } +} diff --git a/src/main/java/chess/view/ConsoleOutputView.java b/src/main/java/chess/view/ConsoleOutputView.java index 9ed1c865145..d9208378aae 100644 --- a/src/main/java/chess/view/ConsoleOutputView.java +++ b/src/main/java/chess/view/ConsoleOutputView.java @@ -4,20 +4,27 @@ import java.util.Map; public class ConsoleOutputView implements OutputView { + private static final String EMPTY_SQUARE = "."; + private static final int MAX_BOARD_SIZE = 8; + @Override - public void printBoard(List positions, Map board) { + public void printBoard(final List positions, final Map board) { for (int i = 1; i <= positions.size(); i++) { String piece = board.get(positions.get(i - 1)); System.out.print(printPiece(piece)); - if (i % 8 == 0) { - System.out.println(); - } + checkNewLine(i); + } + } + + private void checkNewLine(final int i) { + if (i % MAX_BOARD_SIZE == 0) { + System.out.println(); } } private String printPiece(String piece) { if (piece == null) { - return "."; + return EMPTY_SQUARE; } return piece; } diff --git a/src/main/java/chess/view/InputView.java b/src/main/java/chess/view/InputView.java new file mode 100644 index 00000000000..9581c3801f1 --- /dev/null +++ b/src/main/java/chess/view/InputView.java @@ -0,0 +1,5 @@ +package chess.view; + +public interface InputView { + boolean askChessRun(); +} From 3dcf3f958311282188df05e32fdbac3f09a224b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=98=88=EB=B9=88?= Date: Wed, 25 Mar 2020 19:25:08 +0900 Subject: [PATCH 06/29] =?UTF-8?q?feat:=20=EC=9D=B4=EB=8F=99=20=EC=A0=84?= =?UTF-8?q?=EB=9E=B5=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chess/domain/move/BishopMoveStrategy.java | 18 +++++++++++++ .../chess/domain/move/KingMoveStrategy.java | 18 +++++++++++++ .../chess/domain/move/KnightMoveStrategy.java | 17 +++++++++++++ .../java/chess/domain/move/MoveStrategy.java | 13 ++++++++++ .../chess/domain/move/PawnMoveStrategy.java | 18 +++++++++++++ .../chess/domain/move/QueenMoveStrategy.java | 12 +++++++++ .../chess/domain/move/RookMoveStrategy.java | 17 +++++++++++++ .../java/chess/domain/piece/PieceType.java | 20 +++++++++------ src/main/java/chess/domain/position/File.java | 24 +++++++++--------- .../java/chess/domain/position/Position.java | 25 +++++++++++++++++++ src/main/java/chess/domain/position/Rank.java | 8 +++--- 11 files changed, 166 insertions(+), 24 deletions(-) create mode 100644 src/main/java/chess/domain/move/BishopMoveStrategy.java create mode 100644 src/main/java/chess/domain/move/KingMoveStrategy.java create mode 100644 src/main/java/chess/domain/move/KnightMoveStrategy.java create mode 100644 src/main/java/chess/domain/move/MoveStrategy.java create mode 100644 src/main/java/chess/domain/move/PawnMoveStrategy.java create mode 100644 src/main/java/chess/domain/move/QueenMoveStrategy.java create mode 100644 src/main/java/chess/domain/move/RookMoveStrategy.java diff --git a/src/main/java/chess/domain/move/BishopMoveStrategy.java b/src/main/java/chess/domain/move/BishopMoveStrategy.java new file mode 100644 index 00000000000..bbf8b3b7ab8 --- /dev/null +++ b/src/main/java/chess/domain/move/BishopMoveStrategy.java @@ -0,0 +1,18 @@ +package chess.domain.move; + +import chess.domain.position.Position; + +public class BishopMoveStrategy extends MoveStrategy { + + @Override + public boolean movable(Position source, Position target) { + if (isSamePosition(source, target)) { + return false; + } + + int fileGap = Math.abs(source.calculateFileGap(target)); + int rankGap = Math.abs(source.calculateRankGap(target)); + + return fileGap == rankGap; + } +} diff --git a/src/main/java/chess/domain/move/KingMoveStrategy.java b/src/main/java/chess/domain/move/KingMoveStrategy.java new file mode 100644 index 00000000000..789b5f53f73 --- /dev/null +++ b/src/main/java/chess/domain/move/KingMoveStrategy.java @@ -0,0 +1,18 @@ +package chess.domain.move; + +import chess.domain.position.Position; + +public class KingMoveStrategy extends MoveStrategy { + + @Override + public boolean movable(Position source, Position target) { + if (isSamePosition(source, target)) { + return false; + } + + int fileGap = Math.abs(source.calculateFileGap(target)); + int rankGap = Math.abs(source.calculateRankGap(target)); + + return fileGap <= 1 && rankGap <= 1; + } +} diff --git a/src/main/java/chess/domain/move/KnightMoveStrategy.java b/src/main/java/chess/domain/move/KnightMoveStrategy.java new file mode 100644 index 00000000000..b1814787293 --- /dev/null +++ b/src/main/java/chess/domain/move/KnightMoveStrategy.java @@ -0,0 +1,17 @@ +package chess.domain.move; + +import chess.domain.position.Position; + +public class KnightMoveStrategy extends MoveStrategy { + @Override + public boolean movable(Position source, Position target) { + if (isSamePosition(source, target)) { + return false; + } + + int fileGap = Math.abs(source.calculateFileGap(target)); + int rankGap = Math.abs(source.calculateRankGap(target)); + + return fileGap <= 1 && rankGap <= 1; + } +} \ No newline at end of file diff --git a/src/main/java/chess/domain/move/MoveStrategy.java b/src/main/java/chess/domain/move/MoveStrategy.java new file mode 100644 index 00000000000..3f741626568 --- /dev/null +++ b/src/main/java/chess/domain/move/MoveStrategy.java @@ -0,0 +1,13 @@ +package chess.domain.move; + +import chess.domain.position.Position; + +public abstract class MoveStrategy { + + protected abstract boolean movable(Position source, Position target); + + protected boolean isSamePosition(Position source, Position target) { + return source.equals(target); + } + +} diff --git a/src/main/java/chess/domain/move/PawnMoveStrategy.java b/src/main/java/chess/domain/move/PawnMoveStrategy.java new file mode 100644 index 00000000000..673eec2c9a0 --- /dev/null +++ b/src/main/java/chess/domain/move/PawnMoveStrategy.java @@ -0,0 +1,18 @@ +package chess.domain.move; + +import chess.domain.position.Position; + +public class PawnMoveStrategy extends MoveStrategy { + + @Override + public boolean movable(Position source, Position target) { + if (isSamePosition(source, target)) { + return false; + } + + int fileGap = Math.abs(source.calculateFileGap(target)); + int rankGap = Math.abs(source.calculateRankGap(target)); + + return fileGap <= 1 && rankGap <= 1; + } +} \ No newline at end of file diff --git a/src/main/java/chess/domain/move/QueenMoveStrategy.java b/src/main/java/chess/domain/move/QueenMoveStrategy.java new file mode 100644 index 00000000000..f03231668bc --- /dev/null +++ b/src/main/java/chess/domain/move/QueenMoveStrategy.java @@ -0,0 +1,12 @@ +package chess.domain.move; + +import chess.domain.position.Position; + +public class QueenMoveStrategy extends MoveStrategy { + + @Override + public boolean movable(Position source, Position target) { + return new RookMoveStrategy().movable(source, target) + && new BishopMoveStrategy().movable(source, target); + } +} \ No newline at end of file diff --git a/src/main/java/chess/domain/move/RookMoveStrategy.java b/src/main/java/chess/domain/move/RookMoveStrategy.java new file mode 100644 index 00000000000..151bd9117aa --- /dev/null +++ b/src/main/java/chess/domain/move/RookMoveStrategy.java @@ -0,0 +1,17 @@ +package chess.domain.move; + +import chess.domain.position.Position; + +public class RookMoveStrategy extends MoveStrategy { + @Override + public boolean movable(Position source, Position target) { + if (isSamePosition(source, target)) { + return false; + } + + int fileGap = Math.abs(source.calculateFileGap(target)); + int rankGap = Math.abs(source.calculateRankGap(target)); + + return fileGap == 0 && rankGap > 0; + } +} diff --git a/src/main/java/chess/domain/piece/PieceType.java b/src/main/java/chess/domain/piece/PieceType.java index cfe6e8a92cb..414db71cb5c 100644 --- a/src/main/java/chess/domain/piece/PieceType.java +++ b/src/main/java/chess/domain/piece/PieceType.java @@ -1,22 +1,26 @@ package chess.domain.piece; +import chess.domain.move.*; + public enum PieceType { - KING("k", 0), - QUEEN("q", 9), - ROOK("r", 5), - BISHOP("b", 3), - KNIGHT("n", 2.5), - PAWN("p", 1); + KING("k", 0, new KingMoveStrategy()), + QUEEN("q", 9, new QueenMoveStrategy()), + ROOK("r", 5, new RookMoveStrategy()), + BISHOP("b", 3, new BishopMoveStrategy()), + KNIGHT("n", 2.5, new KnightMoveStrategy()), + PAWN("p", 1, new PawnMoveStrategy()); private final String symbol; private final double score; + private final MoveStrategy moveStrategy; - PieceType(String symbol, double score) { + PieceType(String symbol, double score, MoveStrategy moveStrategy) { this.symbol = symbol; this.score = score; + this.moveStrategy = moveStrategy; } public String getSymbol() { return symbol; } -} +} \ No newline at end of file diff --git a/src/main/java/chess/domain/position/File.java b/src/main/java/chess/domain/position/File.java index d4212488217..2646ac73daa 100644 --- a/src/main/java/chess/domain/position/File.java +++ b/src/main/java/chess/domain/position/File.java @@ -3,24 +3,24 @@ import java.util.Arrays; public enum File { - A("a"), - B("b"), - C("c"), - D("d"), - E("e"), - F("f"), - G("g"), - H("h"); + A('a'), + B('b'), + C('c'), + D('d'), + E('e'), + F('f'), + G('g'), + H('h'); - private final String name; + private final char symbol; - File(String name) { - this.name = name; + File(char symbol) { + this.symbol = symbol; } public static File of(String file) { return Arrays.stream(values()) - .filter(ph -> ph.name.equals(file.toLowerCase())) + .filter(ph -> ph.symbol == file.toLowerCase().charAt(0)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("잘못된 x 좌표값을 입력하였습니다.")); } diff --git a/src/main/java/chess/domain/position/Position.java b/src/main/java/chess/domain/position/Position.java index 0f51e44f09e..b9695fa9826 100644 --- a/src/main/java/chess/domain/position/Position.java +++ b/src/main/java/chess/domain/position/Position.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Objects; import java.util.stream.Collectors; public class Position { @@ -50,8 +51,32 @@ public static List getPositions() { return Collections.unmodifiableList(parseResult); } + public int calculateFileGap(Position target) { + int fileGap = this.file.compareTo(target.file); + return fileGap; + } + + public int calculateRankGap(Position target) { + int rankGap = this.rank.compareTo(target.rank); + return rankGap; + } + @Override public String toString() { return file.name() + rank.name(); } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Position position = (Position) o; + return file == position.file && + rank == position.rank; + } + + @Override + public int hashCode() { + return Objects.hash(file, rank); + } } diff --git a/src/main/java/chess/domain/position/Rank.java b/src/main/java/chess/domain/position/Rank.java index 6d0c3c582eb..e006e8c7f5c 100644 --- a/src/main/java/chess/domain/position/Rank.java +++ b/src/main/java/chess/domain/position/Rank.java @@ -12,15 +12,15 @@ public enum Rank { TWO(2), ONE(1); - private final int rank; + private final int symbol; - Rank(int rank) { - this.rank = rank; + Rank(int symbol) { + this.symbol = symbol; } public static Rank of(String rank) { return Arrays.stream(values()) - .filter(pv -> pv.rank == Integer.parseInt(rank)) + .filter(pv -> pv.symbol == Integer.parseInt(rank)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("잘못된 y 좌표값을 입력하였습니다.")); } From b0392f37e70d7fe5f9334809aa5dfe2e6dffe7cd Mon Sep 17 00:00:00 2001 From: giantim Date: Wed, 25 Mar 2020 20:30:13 +0900 Subject: [PATCH 07/29] =?UTF-8?q?feat:=20=ED=8F=B0=EC=9D=98=20=EC=9D=B4?= =?UTF-8?q?=EB=8F=99=20=EC=A0=84=EB=9E=B5=EA=B3=BC=20=ED=8C=80=EB=B3=84=20?= =?UTF-8?q?=EC=9D=B4=EB=8F=99=20=EC=A0=84=EB=9E=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chess/controller/ChessController.java | 5 ++++ src/main/java/chess/domain/board/Board.java | 20 ++++++++++++++++ .../chess/domain/board/BoardInitializer.java | 2 +- .../chess/domain/move/KnightMoveStrategy.java | 2 +- .../java/chess/domain/move/MoveStrategy.java | 3 +-- .../domain/move/MoveStrategyFactory.java | 10 ++++++++ .../chess/domain/move/PawnMoveStrategy.java | 5 ++++ src/main/java/chess/domain/piece/Piece.java | 10 ++++++++ .../java/chess/domain/piece/PieceType.java | 5 ++++ src/main/java/chess/domain/piece/Team.java | 7 ++++++ .../java/chess/view/ConsoleInputView.java | 24 +++++++++++++++++-- src/main/java/chess/view/InputView.java | 1 + 12 files changed, 88 insertions(+), 6 deletions(-) create mode 100644 src/main/java/chess/domain/move/MoveStrategyFactory.java diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index d75a0b61b39..7e112174b34 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -17,6 +17,11 @@ public static void run() { if (inputView.askChessRun()) { Board board = new Board(); printInitialize(board); + String[] moveSource = inputView.askMove().split(" "); + String sourcePosition = moveSource[1]; + String targetPosition = moveSource[2]; + board.updateBoard(sourcePosition, targetPosition); + printInitialize(board); } } diff --git a/src/main/java/chess/domain/board/Board.java b/src/main/java/chess/domain/board/Board.java index df7d71e2bf1..4cbf79a936b 100644 --- a/src/main/java/chess/domain/board/Board.java +++ b/src/main/java/chess/domain/board/Board.java @@ -1,6 +1,7 @@ package chess.domain.board; import chess.domain.piece.Piece; +import chess.domain.piece.Team; import chess.domain.position.Position; import java.util.Collections; @@ -11,8 +12,11 @@ public class Board { private final Map board; + private Team team; + public Board() { this.board = BoardInitializer.initializeAll(); + this.team = Team.WHITE; } public Map parse() { @@ -23,4 +27,20 @@ public Map parse() { (e1, e2) -> e1, LinkedHashMap::new)); return Collections.unmodifiableMap(parseResult); } + + public void updateBoard(String source, String target) { + Position sourcePosition = Position.of(source); + Position targetPosition = Position.of(target); + Piece movedPiece = this.board.get(sourcePosition); + if (!movedPiece.move(sourcePosition, targetPosition)) { + throw new IllegalArgumentException("이동할 수 없는 곳입니다."); + } + this.board.put(targetPosition, movedPiece); + this.board.remove(sourcePosition); + changeTurn(); + } + + private void changeTurn() { + this.team = Team.changeTurn(this.team); + } } diff --git a/src/main/java/chess/domain/board/BoardInitializer.java b/src/main/java/chess/domain/board/BoardInitializer.java index 573184ac6fd..614699b0424 100644 --- a/src/main/java/chess/domain/board/BoardInitializer.java +++ b/src/main/java/chess/domain/board/BoardInitializer.java @@ -27,6 +27,6 @@ public static Map initializeAll() { board.putAll(strategy.initialize()); } - return Collections.unmodifiableMap(board); + return board; } } diff --git a/src/main/java/chess/domain/move/KnightMoveStrategy.java b/src/main/java/chess/domain/move/KnightMoveStrategy.java index b1814787293..bd607700b67 100644 --- a/src/main/java/chess/domain/move/KnightMoveStrategy.java +++ b/src/main/java/chess/domain/move/KnightMoveStrategy.java @@ -12,6 +12,6 @@ public boolean movable(Position source, Position target) { int fileGap = Math.abs(source.calculateFileGap(target)); int rankGap = Math.abs(source.calculateRankGap(target)); - return fileGap <= 1 && rankGap <= 1; + return (fileGap == 2 && rankGap == 1) || (fileGap == 1 && rankGap == 2); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/move/MoveStrategy.java b/src/main/java/chess/domain/move/MoveStrategy.java index 3f741626568..2296bb1963b 100644 --- a/src/main/java/chess/domain/move/MoveStrategy.java +++ b/src/main/java/chess/domain/move/MoveStrategy.java @@ -4,10 +4,9 @@ public abstract class MoveStrategy { - protected abstract boolean movable(Position source, Position target); - protected boolean isSamePosition(Position source, Position target) { return source.equals(target); } + public abstract boolean movable(Position source, Position target); } diff --git a/src/main/java/chess/domain/move/MoveStrategyFactory.java b/src/main/java/chess/domain/move/MoveStrategyFactory.java new file mode 100644 index 00000000000..0ca7e3ff23f --- /dev/null +++ b/src/main/java/chess/domain/move/MoveStrategyFactory.java @@ -0,0 +1,10 @@ +package chess.domain.move; + +import chess.domain.piece.PieceType; +import chess.domain.piece.Team; + +public class MoveStrategyFactory { +// public static MoveStrategy create(PieceType pieceType, Team team) { +// +// } +} diff --git a/src/main/java/chess/domain/move/PawnMoveStrategy.java b/src/main/java/chess/domain/move/PawnMoveStrategy.java index 673eec2c9a0..f1423e1b14d 100644 --- a/src/main/java/chess/domain/move/PawnMoveStrategy.java +++ b/src/main/java/chess/domain/move/PawnMoveStrategy.java @@ -1,8 +1,13 @@ package chess.domain.move; +import chess.domain.piece.Team; import chess.domain.position.Position; public class PawnMoveStrategy extends MoveStrategy { + private static final int WHITE_POSITION = 2; + private static final int BLACK_POSITION = 7; + + private Team team; @Override public boolean movable(Position source, Position target) { diff --git a/src/main/java/chess/domain/piece/Piece.java b/src/main/java/chess/domain/piece/Piece.java index 68b661d453e..39c5bae1b38 100644 --- a/src/main/java/chess/domain/piece/Piece.java +++ b/src/main/java/chess/domain/piece/Piece.java @@ -1,15 +1,25 @@ package chess.domain.piece; +import chess.domain.move.MoveStrategy; +import chess.domain.move.MoveStrategyFactory; +import chess.domain.position.Position; + public class Piece { private final PieceType pieceType; private final Team team; +// private final MoveStrategy moveStrategy; public Piece(final PieceType pieceType, final Team team) { this.pieceType = pieceType; this.team = team; +// this.moveStrategy = MoveStrategyFactory.create(pieceType, team); } public String toSymbol() { return this.team.convert(this.pieceType.getSymbol()); } + + public boolean move(Position source, Position target) { + return this.pieceType.move(source, target); + } } diff --git a/src/main/java/chess/domain/piece/PieceType.java b/src/main/java/chess/domain/piece/PieceType.java index 414db71cb5c..3d63b5401a4 100644 --- a/src/main/java/chess/domain/piece/PieceType.java +++ b/src/main/java/chess/domain/piece/PieceType.java @@ -1,6 +1,7 @@ package chess.domain.piece; import chess.domain.move.*; +import chess.domain.position.Position; public enum PieceType { KING("k", 0, new KingMoveStrategy()), @@ -23,4 +24,8 @@ public enum PieceType { public String getSymbol() { return symbol; } + + public boolean move(Position source, Position target) { + return this.moveStrategy.movable(source, target); + } } \ No newline at end of file diff --git a/src/main/java/chess/domain/piece/Team.java b/src/main/java/chess/domain/piece/Team.java index ec97b6aa539..ace859b507f 100644 --- a/src/main/java/chess/domain/piece/Team.java +++ b/src/main/java/chess/domain/piece/Team.java @@ -12,6 +12,13 @@ public enum Team { this.expression = expression; } + public static Team changeTurn(Team team) { + if (team == BLACK) { + return WHITE; + } + return BLACK; + } + public String convert(final String name) { return this.expression.apply(name); } diff --git a/src/main/java/chess/view/ConsoleInputView.java b/src/main/java/chess/view/ConsoleInputView.java index 3daac277af9..3dc45472fba 100644 --- a/src/main/java/chess/view/ConsoleInputView.java +++ b/src/main/java/chess/view/ConsoleInputView.java @@ -9,9 +9,11 @@ public class ConsoleInputView implements InputView { @Override public boolean askChessRun() { + System.out.println("> 체스 게임을 시작합니다."); + System.out.println("> 게임 시작 : start"); + System.out.println("> 게임 종료 : end"); + System.out.println("> 게임 이동 : move source위치 target위치 - 예. move b2 b3"); try { - System.out.println("체스 게임을 시작합니다."); - System.out.println("게임 시작은 start, 종료는 end 명령어를 입력하세요."); String input = SCANNER.nextLine(); validateCommand(input); return runFlag(input); @@ -33,4 +35,22 @@ private boolean runFlag(String input) { } return false; } + + @Override + public String askMove() { + try { + String input = SCANNER.nextLine(); + validateMove(input); + return input; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return askMove(); + } + } + + private static void validateMove(String input) { + if (!input.contains("move")) { + throw new IllegalArgumentException("잘못된 명령어를 입력하였습니다."); + } + } } diff --git a/src/main/java/chess/view/InputView.java b/src/main/java/chess/view/InputView.java index 9581c3801f1..6d6ef517950 100644 --- a/src/main/java/chess/view/InputView.java +++ b/src/main/java/chess/view/InputView.java @@ -2,4 +2,5 @@ public interface InputView { boolean askChessRun(); + String askMove(); } From 08ab69b8478ce71a067465c41f186d0822592161 Mon Sep 17 00:00:00 2001 From: giantim Date: Thu, 26 Mar 2020 15:19:47 +0900 Subject: [PATCH 08/29] =?UTF-8?q?feat:=20=EB=A7=90=20=EC=9D=B4=EB=8F=99=20?= =?UTF-8?q?=EC=8B=9C=20=EC=9E=A5=EC=95=A0=EB=AC=BC=20=ED=83=90=EC=83=89=20?= =?UTF-8?q?=20=20=20=20-=20=EA=B2=8C=EC=9E=84=EC=9D=84=20=EC=A7=84?= =?UTF-8?q?=ED=96=89=ED=95=98=EB=8A=94=20ChessRunner=20=ED=81=B4=EB=9E=98?= =?UTF-8?q?=EC=8A=A4=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chess/controller/ChessController.java | 9 ++-- src/main/java/chess/domain/ChessRunner.java | 43 +++++++++++++++++++ src/main/java/chess/domain/board/Board.java | 24 ++++------- .../chess/domain/move/BishopMoveStrategy.java | 7 ++- .../chess/domain/move/KingMoveStrategy.java | 4 +- .../chess/domain/move/KnightMoveStrategy.java | 3 +- .../java/chess/domain/move/MoveStrategy.java | 28 +++++++++++- .../domain/move/MoveStrategyFactory.java | 10 ----- .../java/chess/domain/move/PathFinder.java | 39 +++++++++++++++++ .../chess/domain/move/PawnMoveStrategy.java | 38 +++++++++++++--- .../chess/domain/move/QueenMoveStrategy.java | 7 +-- .../chess/domain/move/RookMoveStrategy.java | 8 +++- .../move/direction/DirectionStrategy.java | 9 ++++ .../domain/move/direction/DownStrategy.java | 18 ++++++++ .../domain/move/direction/UpStrategy.java | 18 ++++++++ src/main/java/chess/domain/piece/Piece.java | 15 +++++-- .../java/chess/domain/piece/PieceType.java | 5 ++- src/main/java/chess/domain/piece/Team.java | 8 ++++ src/main/java/chess/domain/position/File.java | 13 +++++- .../java/chess/domain/position/Position.java | 18 ++++++++ src/main/java/chess/domain/position/Rank.java | 11 +++++ 21 files changed, 283 insertions(+), 52 deletions(-) create mode 100644 src/main/java/chess/domain/ChessRunner.java delete mode 100644 src/main/java/chess/domain/move/MoveStrategyFactory.java create mode 100644 src/main/java/chess/domain/move/PathFinder.java create mode 100644 src/main/java/chess/domain/move/direction/DirectionStrategy.java create mode 100644 src/main/java/chess/domain/move/direction/DownStrategy.java create mode 100644 src/main/java/chess/domain/move/direction/UpStrategy.java diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index 7e112174b34..6590998b01b 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -2,6 +2,7 @@ import chess.controller.dto.BoardDto; import chess.controller.dto.PositionDto; +import chess.domain.ChessRunner; import chess.domain.board.Board; import chess.domain.position.Position; import chess.view.ConsoleInputView; @@ -15,13 +16,13 @@ public class ChessController { public static void run() { if (inputView.askChessRun()) { - Board board = new Board(); - printInitialize(board); + ChessRunner chessRunner = new ChessRunner(); + printInitialize(chessRunner.getBoard()); String[] moveSource = inputView.askMove().split(" "); String sourcePosition = moveSource[1]; String targetPosition = moveSource[2]; - board.updateBoard(sourcePosition, targetPosition); - printInitialize(board); + chessRunner.update(sourcePosition, targetPosition); + printInitialize(chessRunner.getBoard()); } } diff --git a/src/main/java/chess/domain/ChessRunner.java b/src/main/java/chess/domain/ChessRunner.java new file mode 100644 index 00000000000..ef332ef0b00 --- /dev/null +++ b/src/main/java/chess/domain/ChessRunner.java @@ -0,0 +1,43 @@ +package chess.domain; + +import chess.domain.board.Board; +import chess.domain.piece.Piece; +import chess.domain.piece.Team; +import chess.domain.position.Position; + +public class ChessRunner { + private Board board; + private Team currentTeam; + + public ChessRunner() { + this.board = new Board(); + this.currentTeam = Team.WHITE; + } + + public void update(String source, String target) { + Position sourcePosition = Position.of(source); + Position targetPosition = Position.of(target); + Piece selectedPiece = this.board.getPiece(sourcePosition); + + if (!(currentTeam.isEnemy(selectedPiece.getTeam()))) { + throw new IllegalArgumentException("현재 차례가 아닙니다."); + } + + if (!(selectedPiece.move(sourcePosition, targetPosition, board))) { + throw new IllegalArgumentException("이동할 수 없는 곳입니다."); + } + + this.board.updateBoard(sourcePosition, targetPosition, selectedPiece); + + changeTurn(); + + } + + private void changeTurn() { + this.currentTeam = Team.changeTurn(this.currentTeam); + } + + public Board getBoard() { + return this.board; + } +} diff --git a/src/main/java/chess/domain/board/Board.java b/src/main/java/chess/domain/board/Board.java index 4cbf79a936b..e98ce9021fc 100644 --- a/src/main/java/chess/domain/board/Board.java +++ b/src/main/java/chess/domain/board/Board.java @@ -12,11 +12,8 @@ public class Board { private final Map board; - private Team team; - public Board() { this.board = BoardInitializer.initializeAll(); - this.team = Team.WHITE; } public Map parse() { @@ -28,19 +25,16 @@ public Map parse() { return Collections.unmodifiableMap(parseResult); } - public void updateBoard(String source, String target) { - Position sourcePosition = Position.of(source); - Position targetPosition = Position.of(target); - Piece movedPiece = this.board.get(sourcePosition); - if (!movedPiece.move(sourcePosition, targetPosition)) { - throw new IllegalArgumentException("이동할 수 없는 곳입니다."); - } - this.board.put(targetPosition, movedPiece); + public void updateBoard(Position sourcePosition, Position targetPosition, Piece selectedPiece) { + this.board.put(targetPosition, selectedPiece); this.board.remove(sourcePosition); - changeTurn(); } - private void changeTurn() { - this.team = Team.changeTurn(this.team); + public boolean isEmpty(final Position position) { + return this.board.containsKey(position); + } + + public Piece getPiece(final Position position) { + return this.board.get(position); } -} +} \ No newline at end of file diff --git a/src/main/java/chess/domain/move/BishopMoveStrategy.java b/src/main/java/chess/domain/move/BishopMoveStrategy.java index bbf8b3b7ab8..f63996a5f23 100644 --- a/src/main/java/chess/domain/move/BishopMoveStrategy.java +++ b/src/main/java/chess/domain/move/BishopMoveStrategy.java @@ -1,11 +1,12 @@ package chess.domain.move; +import chess.domain.board.Board; import chess.domain.position.Position; public class BishopMoveStrategy extends MoveStrategy { @Override - public boolean movable(Position source, Position target) { + public boolean movable(Position source, Position target, Board board) { if (isSamePosition(source, target)) { return false; } @@ -13,6 +14,8 @@ public boolean movable(Position source, Position target) { int fileGap = Math.abs(source.calculateFileGap(target)); int rankGap = Math.abs(source.calculateRankGap(target)); - return fileGap == rankGap; + return fileGap == rankGap + && checkObstacle(source, target, board) + && checkTarget(source, target, board); } } diff --git a/src/main/java/chess/domain/move/KingMoveStrategy.java b/src/main/java/chess/domain/move/KingMoveStrategy.java index 789b5f53f73..fda5384ee5b 100644 --- a/src/main/java/chess/domain/move/KingMoveStrategy.java +++ b/src/main/java/chess/domain/move/KingMoveStrategy.java @@ -1,11 +1,13 @@ package chess.domain.move; +import chess.domain.board.Board; +import chess.domain.piece.Piece; import chess.domain.position.Position; public class KingMoveStrategy extends MoveStrategy { @Override - public boolean movable(Position source, Position target) { + public boolean movable(Position source, Position target, Board board) { if (isSamePosition(source, target)) { return false; } diff --git a/src/main/java/chess/domain/move/KnightMoveStrategy.java b/src/main/java/chess/domain/move/KnightMoveStrategy.java index bd607700b67..fb917dbfadf 100644 --- a/src/main/java/chess/domain/move/KnightMoveStrategy.java +++ b/src/main/java/chess/domain/move/KnightMoveStrategy.java @@ -1,10 +1,11 @@ package chess.domain.move; +import chess.domain.board.Board; import chess.domain.position.Position; public class KnightMoveStrategy extends MoveStrategy { @Override - public boolean movable(Position source, Position target) { + public boolean movable(Position source, Position target, Board board) { if (isSamePosition(source, target)) { return false; } diff --git a/src/main/java/chess/domain/move/MoveStrategy.java b/src/main/java/chess/domain/move/MoveStrategy.java index 2296bb1963b..77524596c9e 100644 --- a/src/main/java/chess/domain/move/MoveStrategy.java +++ b/src/main/java/chess/domain/move/MoveStrategy.java @@ -1,12 +1,38 @@ package chess.domain.move; +import chess.domain.board.Board; +import chess.domain.move.direction.DirectionStrategy; +import chess.domain.piece.Piece; import chess.domain.position.Position; +import java.util.List; + public abstract class MoveStrategy { protected boolean isSamePosition(Position source, Position target) { return source.equals(target); } - public abstract boolean movable(Position source, Position target); + public abstract boolean movable(Position source, Position target, Board board); + + protected boolean checkObstacle(Position source, Position target, Board board) { + DirectionStrategy directionStrategy= PathFinder.find(source, target); + List path = directionStrategy.find(source, target); + + for (Position position : path) { + if (!board.isEmpty(position)) { + return false; + } + } + return true; + } + + protected boolean checkTarget(Position source, Position target, Board board) { + Piece sourcePiece = board.getPiece(source); + if (board.isEmpty(target)) { + return true; + } + Piece targetPiece = board.getPiece(target); + return sourcePiece.isEnemy(targetPiece); + } } diff --git a/src/main/java/chess/domain/move/MoveStrategyFactory.java b/src/main/java/chess/domain/move/MoveStrategyFactory.java deleted file mode 100644 index 0ca7e3ff23f..00000000000 --- a/src/main/java/chess/domain/move/MoveStrategyFactory.java +++ /dev/null @@ -1,10 +0,0 @@ -package chess.domain.move; - -import chess.domain.piece.PieceType; -import chess.domain.piece.Team; - -public class MoveStrategyFactory { -// public static MoveStrategy create(PieceType pieceType, Team team) { -// -// } -} diff --git a/src/main/java/chess/domain/move/PathFinder.java b/src/main/java/chess/domain/move/PathFinder.java new file mode 100644 index 00000000000..0c9c4358fdc --- /dev/null +++ b/src/main/java/chess/domain/move/PathFinder.java @@ -0,0 +1,39 @@ +package chess.domain.move; + +import chess.domain.move.direction.DirectionStrategy; +import chess.domain.move.direction.DownStrategy; +import chess.domain.move.direction.UpStrategy; +import chess.domain.position.Position; + +public class PathFinder { + public static DirectionStrategy find(Position source, Position target) { + int fileGap = target.calculateFileGap(source); + int rankGap = target.calculateRankGap(source); + + if (fileGap == 0 && rankGap > 0) { + return new UpStrategy(); + } + if (fileGap == 0 && rankGap < 0) { + return new DownStrategy(); + } + if (fileGap > 0 && rankGap == 0) { + + } + if (fileGap < 0 && rankGap == 0) { + + } + if (fileGap > 0 && rankGap > 0) { + + } + if (fileGap > 0 && rankGap < 0) { + + } + if (fileGap < 0 && rankGap > 0) { + + } + if (fileGap < 0 && rankGap < 0) { + + } + return null; + } +} diff --git a/src/main/java/chess/domain/move/PawnMoveStrategy.java b/src/main/java/chess/domain/move/PawnMoveStrategy.java index f1423e1b14d..58981836295 100644 --- a/src/main/java/chess/domain/move/PawnMoveStrategy.java +++ b/src/main/java/chess/domain/move/PawnMoveStrategy.java @@ -1,5 +1,7 @@ package chess.domain.move; +import chess.domain.board.Board; +import chess.domain.piece.Piece; import chess.domain.piece.Team; import chess.domain.position.Position; @@ -7,17 +9,41 @@ public class PawnMoveStrategy extends MoveStrategy { private static final int WHITE_POSITION = 2; private static final int BLACK_POSITION = 7; - private Team team; - @Override - public boolean movable(Position source, Position target) { + public boolean movable(Position source, Position target, Board board) { if (isSamePosition(source, target)) { return false; } - int fileGap = Math.abs(source.calculateFileGap(target)); - int rankGap = Math.abs(source.calculateRankGap(target)); + int fileGap = source.calculateFileGap(target); + int rankGap = source.calculateRankGap(target); + + Piece sourcePiece = board.getPiece(source); + Piece targetPiece = board.getPiece(target); + Team pawnTeam = sourcePiece.getTeam(); - return fileGap <= 1 && rankGap <= 1; + if (pawnTeam.isWhite()) { + if (fileGap == 0 && rankGap == -1) { + return board.isEmpty(target); + } + if (fileGap == 0 && rankGap == -2) { + return source.getRank() == WHITE_POSITION; + } + if (Math.abs(fileGap) == 1 && rankGap == -1) { + return !board.isEmpty(target) && sourcePiece.isEnemy(targetPiece); + } + } + if (!pawnTeam.isWhite()) { + if (fileGap == 0 && rankGap == 1) { + return board.isEmpty(target); + } + if (fileGap == 0 && rankGap == 2) { + return source.getRank() == BLACK_POSITION; + } + if (Math.abs(fileGap) == 1 && rankGap == 1) { + return !board.isEmpty(target) && sourcePiece.isEnemy(targetPiece); + } + } + return false; } } \ No newline at end of file diff --git a/src/main/java/chess/domain/move/QueenMoveStrategy.java b/src/main/java/chess/domain/move/QueenMoveStrategy.java index f03231668bc..55442763d21 100644 --- a/src/main/java/chess/domain/move/QueenMoveStrategy.java +++ b/src/main/java/chess/domain/move/QueenMoveStrategy.java @@ -1,12 +1,13 @@ package chess.domain.move; +import chess.domain.board.Board; import chess.domain.position.Position; public class QueenMoveStrategy extends MoveStrategy { @Override - public boolean movable(Position source, Position target) { - return new RookMoveStrategy().movable(source, target) - && new BishopMoveStrategy().movable(source, target); + public boolean movable(Position source, Position target, Board board) { + return new RookMoveStrategy().movable(source, target, board) + && new BishopMoveStrategy().movable(source, target, board); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/move/RookMoveStrategy.java b/src/main/java/chess/domain/move/RookMoveStrategy.java index 151bd9117aa..87e435b5735 100644 --- a/src/main/java/chess/domain/move/RookMoveStrategy.java +++ b/src/main/java/chess/domain/move/RookMoveStrategy.java @@ -1,10 +1,14 @@ package chess.domain.move; +import chess.domain.board.Board; +import chess.domain.move.direction.DirectionStrategy; import chess.domain.position.Position; +import java.util.List; + public class RookMoveStrategy extends MoveStrategy { @Override - public boolean movable(Position source, Position target) { + public boolean movable(Position source, Position target, Board board) { if (isSamePosition(source, target)) { return false; } @@ -12,6 +16,6 @@ public boolean movable(Position source, Position target) { int fileGap = Math.abs(source.calculateFileGap(target)); int rankGap = Math.abs(source.calculateRankGap(target)); - return fileGap == 0 && rankGap > 0; + return fileGap == 0 && rankGap > 0 && checkObstacle(source, target, board); } } diff --git a/src/main/java/chess/domain/move/direction/DirectionStrategy.java b/src/main/java/chess/domain/move/direction/DirectionStrategy.java new file mode 100644 index 00000000000..298b0eeed25 --- /dev/null +++ b/src/main/java/chess/domain/move/direction/DirectionStrategy.java @@ -0,0 +1,9 @@ +package chess.domain.move.direction; + +import chess.domain.position.Position; + +import java.util.List; + +public interface DirectionStrategy { + List find(Position source, Position target); +} \ No newline at end of file diff --git a/src/main/java/chess/domain/move/direction/DownStrategy.java b/src/main/java/chess/domain/move/direction/DownStrategy.java new file mode 100644 index 00000000000..6ce3899e91a --- /dev/null +++ b/src/main/java/chess/domain/move/direction/DownStrategy.java @@ -0,0 +1,18 @@ +package chess.domain.move.direction; + +import chess.domain.position.Position; + +import java.util.ArrayList; +import java.util.List; + +public class DownStrategy implements DirectionStrategy { + @Override + public List find(Position source, Position target) { + List path = new ArrayList<>(); + + for (int i = target.getRank() + 1; i < source.getRank(); i++) { + path.add(Position.of(source.getFile(), i)); + } + return path; + } +} \ No newline at end of file diff --git a/src/main/java/chess/domain/move/direction/UpStrategy.java b/src/main/java/chess/domain/move/direction/UpStrategy.java new file mode 100644 index 00000000000..3fd2319d9e8 --- /dev/null +++ b/src/main/java/chess/domain/move/direction/UpStrategy.java @@ -0,0 +1,18 @@ +package chess.domain.move.direction; + +import chess.domain.position.Position; + +import java.util.ArrayList; +import java.util.List; + +public class UpStrategy implements DirectionStrategy { + @Override + public List find(Position source, Position target) { + List path = new ArrayList<>(); + + for (int i = target.getRank() - 1; i > source.getRank(); i--) { + path.add(Position.of(source.getFile(), i)); + } + return path; + } +} \ No newline at end of file diff --git a/src/main/java/chess/domain/piece/Piece.java b/src/main/java/chess/domain/piece/Piece.java index 39c5bae1b38..5286a31b705 100644 --- a/src/main/java/chess/domain/piece/Piece.java +++ b/src/main/java/chess/domain/piece/Piece.java @@ -1,7 +1,6 @@ package chess.domain.piece; -import chess.domain.move.MoveStrategy; -import chess.domain.move.MoveStrategyFactory; +import chess.domain.board.Board; import chess.domain.position.Position; public class Piece { @@ -19,7 +18,15 @@ public String toSymbol() { return this.team.convert(this.pieceType.getSymbol()); } - public boolean move(Position source, Position target) { - return this.pieceType.move(source, target); + public boolean move(Position source, Position target, Board board) { + return this.pieceType.move(source, target, board); + } + + public boolean isEnemy(Piece targetPiece) { + return this.team.isEnemy(targetPiece.getTeam()); + } + + public Team getTeam() { + return this.team; } } diff --git a/src/main/java/chess/domain/piece/PieceType.java b/src/main/java/chess/domain/piece/PieceType.java index 3d63b5401a4..f3e742e3247 100644 --- a/src/main/java/chess/domain/piece/PieceType.java +++ b/src/main/java/chess/domain/piece/PieceType.java @@ -1,5 +1,6 @@ package chess.domain.piece; +import chess.domain.board.Board; import chess.domain.move.*; import chess.domain.position.Position; @@ -25,7 +26,7 @@ public String getSymbol() { return symbol; } - public boolean move(Position source, Position target) { - return this.moveStrategy.movable(source, target); + public boolean move(Position source, Position target, Board board) { + return this.moveStrategy.movable(source, target, board); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/piece/Team.java b/src/main/java/chess/domain/piece/Team.java index ace859b507f..bd6eae9ddb3 100644 --- a/src/main/java/chess/domain/piece/Team.java +++ b/src/main/java/chess/domain/piece/Team.java @@ -22,4 +22,12 @@ public static Team changeTurn(Team team) { public String convert(final String name) { return this.expression.apply(name); } + + public boolean isEnemy(Team team) { + return this != team; + } + + public boolean isWhite() { + return this == WHITE; + } } diff --git a/src/main/java/chess/domain/position/File.java b/src/main/java/chess/domain/position/File.java index 2646ac73daa..0a856960b02 100644 --- a/src/main/java/chess/domain/position/File.java +++ b/src/main/java/chess/domain/position/File.java @@ -20,8 +20,19 @@ public enum File { public static File of(String file) { return Arrays.stream(values()) - .filter(ph -> ph.symbol == file.toLowerCase().charAt(0)) + .filter(f -> f.symbol == file.toLowerCase().charAt(0)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("잘못된 x 좌표값을 입력하였습니다.")); } + + public static File of(int file) { + return Arrays.stream(values()) + .filter(f -> f.symbol == (char) file) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("잘못된 x 좌표값을 입력하였습니다.")); + } + + public int getSymbol() { + return this.symbol; + } } diff --git a/src/main/java/chess/domain/position/Position.java b/src/main/java/chess/domain/position/Position.java index b9695fa9826..29520ae3f02 100644 --- a/src/main/java/chess/domain/position/Position.java +++ b/src/main/java/chess/domain/position/Position.java @@ -44,6 +44,16 @@ private static Position findPosition(File file, Rank rank) { .orElseThrow(AssertionError::new); } + public static Position of(final File file, final Rank rank) { + return findPosition(file, rank); + } + + public static Position of(final int fileSymbol, final int rankSymbol) { + + + return findPosition(File.of(fileSymbol), Rank.of(rankSymbol)); + } + public static List getPositions() { List parseResult = positions.stream() .map(Position::toString) @@ -61,6 +71,14 @@ public int calculateRankGap(Position target) { return rankGap; } + public int getFile() { + return this.file.getSymbol(); + } + + public int getRank() { + return this.rank.getSymbol(); + } + @Override public String toString() { return file.name() + rank.name(); diff --git a/src/main/java/chess/domain/position/Rank.java b/src/main/java/chess/domain/position/Rank.java index e006e8c7f5c..c1cbd0e889c 100644 --- a/src/main/java/chess/domain/position/Rank.java +++ b/src/main/java/chess/domain/position/Rank.java @@ -24,4 +24,15 @@ public static Rank of(String rank) { .findFirst() .orElseThrow(() -> new IllegalArgumentException("잘못된 y 좌표값을 입력하였습니다.")); } + + public static Rank of(int rank) { + return Arrays.stream(values()) + .filter(f -> f.symbol == rank) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("잘못된 x 좌표값을 입력하였습니다.")); + } + + public int getSymbol() { + return this.symbol; + } } From 1d69dbfee24fc619b419d4d894d7792fcb755b6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=98=88=EB=B9=88?= Date: Thu, 26 Mar 2020 15:53:57 +0900 Subject: [PATCH 09/29] =?UTF-8?q?feat:=20=EB=B0=A9=ED=96=A5=20=EC=A0=84?= =?UTF-8?q?=EB=9E=B5=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/domain/ChessRunner.java | 2 +- .../chess/domain/move/BishopMoveStrategy.java | 2 +- .../chess/domain/move/KingMoveStrategy.java | 3 ++- .../chess/domain/move/KnightMoveStrategy.java | 3 ++- .../java/chess/domain/move/PathFinder.java | 18 ++++++------- .../chess/domain/move/QueenMoveStrategy.java | 2 +- .../chess/domain/move/RookMoveStrategy.java | 4 ++- .../move/direction/LeftDownStrategy.java | 20 ++++++++++++++ .../domain/move/direction/LeftStrategy.java | 18 +++++++++++++ .../domain/move/direction/LeftUpStrategy.java | 20 ++++++++++++++ .../move/direction/RightDownStrategy.java | 20 ++++++++++++++ .../domain/move/direction/RightStrategy.java | 18 +++++++++++++ .../move/direction/RightUpStrategy.java | 20 ++++++++++++++ src/main/java/chess/domain/piece/Piece.java | 2 -- src/main/java/chess/domain/position/File.java | 26 ++++++++++++------- .../java/chess/domain/position/Position.java | 4 +-- src/main/java/chess/view/InputView.java | 2 ++ 17 files changed, 153 insertions(+), 31 deletions(-) create mode 100644 src/main/java/chess/domain/move/direction/LeftDownStrategy.java create mode 100644 src/main/java/chess/domain/move/direction/LeftStrategy.java create mode 100644 src/main/java/chess/domain/move/direction/LeftUpStrategy.java create mode 100644 src/main/java/chess/domain/move/direction/RightDownStrategy.java create mode 100644 src/main/java/chess/domain/move/direction/RightStrategy.java create mode 100644 src/main/java/chess/domain/move/direction/RightUpStrategy.java diff --git a/src/main/java/chess/domain/ChessRunner.java b/src/main/java/chess/domain/ChessRunner.java index ef332ef0b00..478814ed72b 100644 --- a/src/main/java/chess/domain/ChessRunner.java +++ b/src/main/java/chess/domain/ChessRunner.java @@ -19,7 +19,7 @@ public void update(String source, String target) { Position targetPosition = Position.of(target); Piece selectedPiece = this.board.getPiece(sourcePosition); - if (!(currentTeam.isEnemy(selectedPiece.getTeam()))) { + if ((currentTeam.isEnemy(selectedPiece.getTeam()))) { throw new IllegalArgumentException("현재 차례가 아닙니다."); } diff --git a/src/main/java/chess/domain/move/BishopMoveStrategy.java b/src/main/java/chess/domain/move/BishopMoveStrategy.java index f63996a5f23..131b5e079da 100644 --- a/src/main/java/chess/domain/move/BishopMoveStrategy.java +++ b/src/main/java/chess/domain/move/BishopMoveStrategy.java @@ -14,7 +14,7 @@ public boolean movable(Position source, Position target, Board board) { int fileGap = Math.abs(source.calculateFileGap(target)); int rankGap = Math.abs(source.calculateRankGap(target)); - return fileGap == rankGap + return (fileGap == rankGap) && checkObstacle(source, target, board) && checkTarget(source, target, board); } diff --git a/src/main/java/chess/domain/move/KingMoveStrategy.java b/src/main/java/chess/domain/move/KingMoveStrategy.java index fda5384ee5b..bc816329df6 100644 --- a/src/main/java/chess/domain/move/KingMoveStrategy.java +++ b/src/main/java/chess/domain/move/KingMoveStrategy.java @@ -15,6 +15,7 @@ public boolean movable(Position source, Position target, Board board) { int fileGap = Math.abs(source.calculateFileGap(target)); int rankGap = Math.abs(source.calculateRankGap(target)); - return fileGap <= 1 && rankGap <= 1; + return (fileGap <= 1 && rankGap <= 1) + && checkTarget(source, target, board); } } diff --git a/src/main/java/chess/domain/move/KnightMoveStrategy.java b/src/main/java/chess/domain/move/KnightMoveStrategy.java index fb917dbfadf..484d2e3ae2d 100644 --- a/src/main/java/chess/domain/move/KnightMoveStrategy.java +++ b/src/main/java/chess/domain/move/KnightMoveStrategy.java @@ -13,6 +13,7 @@ public boolean movable(Position source, Position target, Board board) { int fileGap = Math.abs(source.calculateFileGap(target)); int rankGap = Math.abs(source.calculateRankGap(target)); - return (fileGap == 2 && rankGap == 1) || (fileGap == 1 && rankGap == 2); + return (fileGap == 2 && rankGap == 1) || (fileGap == 1 && rankGap == 2) + && checkTarget(source, target, board); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/move/PathFinder.java b/src/main/java/chess/domain/move/PathFinder.java index 0c9c4358fdc..043af998b1e 100644 --- a/src/main/java/chess/domain/move/PathFinder.java +++ b/src/main/java/chess/domain/move/PathFinder.java @@ -1,8 +1,6 @@ package chess.domain.move; -import chess.domain.move.direction.DirectionStrategy; -import chess.domain.move.direction.DownStrategy; -import chess.domain.move.direction.UpStrategy; +import chess.domain.move.direction.*; import chess.domain.position.Position; public class PathFinder { @@ -17,23 +15,23 @@ public static DirectionStrategy find(Position source, Position target) { return new DownStrategy(); } if (fileGap > 0 && rankGap == 0) { - + return new RightStrategy(); } if (fileGap < 0 && rankGap == 0) { - + return new LeftStrategy(); } if (fileGap > 0 && rankGap > 0) { - + return new RightUpStrategy(); } if (fileGap > 0 && rankGap < 0) { - + return new RightDownStrategy(); } if (fileGap < 0 && rankGap > 0) { - + return new LeftUpStrategy(); } if (fileGap < 0 && rankGap < 0) { - + return new LeftDownStrategy(); } - return null; + throw new AssertionError(); } } diff --git a/src/main/java/chess/domain/move/QueenMoveStrategy.java b/src/main/java/chess/domain/move/QueenMoveStrategy.java index 55442763d21..3cb9525322b 100644 --- a/src/main/java/chess/domain/move/QueenMoveStrategy.java +++ b/src/main/java/chess/domain/move/QueenMoveStrategy.java @@ -8,6 +8,6 @@ public class QueenMoveStrategy extends MoveStrategy { @Override public boolean movable(Position source, Position target, Board board) { return new RookMoveStrategy().movable(source, target, board) - && new BishopMoveStrategy().movable(source, target, board); + || new BishopMoveStrategy().movable(source, target, board); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/move/RookMoveStrategy.java b/src/main/java/chess/domain/move/RookMoveStrategy.java index 87e435b5735..d9db390d72d 100644 --- a/src/main/java/chess/domain/move/RookMoveStrategy.java +++ b/src/main/java/chess/domain/move/RookMoveStrategy.java @@ -16,6 +16,8 @@ public boolean movable(Position source, Position target, Board board) { int fileGap = Math.abs(source.calculateFileGap(target)); int rankGap = Math.abs(source.calculateRankGap(target)); - return fileGap == 0 && rankGap > 0 && checkObstacle(source, target, board); + return (fileGap == 0 && rankGap > 0) + && checkObstacle(source, target, board) + && checkTarget(source, target, board); } } diff --git a/src/main/java/chess/domain/move/direction/LeftDownStrategy.java b/src/main/java/chess/domain/move/direction/LeftDownStrategy.java new file mode 100644 index 00000000000..29dd121a889 --- /dev/null +++ b/src/main/java/chess/domain/move/direction/LeftDownStrategy.java @@ -0,0 +1,20 @@ +package chess.domain.move.direction; + +import chess.domain.position.Position; + +import java.util.ArrayList; +import java.util.List; + +public class LeftDownStrategy implements DirectionStrategy { + + @Override + public List find(Position source, Position target) { + List path = new ArrayList<>(); + + for (int i = target.getFile() + 1 ; i < source.getFile() ; i++) { + path.add(Position.of(i, target.getRank() - (target.getFile() - i))); + } + + return path; + } +} diff --git a/src/main/java/chess/domain/move/direction/LeftStrategy.java b/src/main/java/chess/domain/move/direction/LeftStrategy.java new file mode 100644 index 00000000000..8189c9a41b9 --- /dev/null +++ b/src/main/java/chess/domain/move/direction/LeftStrategy.java @@ -0,0 +1,18 @@ +package chess.domain.move.direction; + +import chess.domain.position.Position; + +import java.util.ArrayList; +import java.util.List; + +public class LeftStrategy implements DirectionStrategy { + @Override + public List find(Position source, Position target) { + List path = new ArrayList<>(); + + for (int i = target.getFile() + 1; i < source.getFile(); i++) { + path.add(Position.of(i, source.getRank())); + } + return path; + } +} \ No newline at end of file diff --git a/src/main/java/chess/domain/move/direction/LeftUpStrategy.java b/src/main/java/chess/domain/move/direction/LeftUpStrategy.java new file mode 100644 index 00000000000..30e0511bbd5 --- /dev/null +++ b/src/main/java/chess/domain/move/direction/LeftUpStrategy.java @@ -0,0 +1,20 @@ +package chess.domain.move.direction; + +import chess.domain.position.File; +import chess.domain.position.Position; + +import java.util.ArrayList; +import java.util.List; + +public class LeftUpStrategy implements DirectionStrategy { + @Override + public List find(Position source, Position target) { + List path = new ArrayList<>(); + + for (int i = target.getFile() + 1 ; i < source.getFile() ; i++) { + path.add(Position.of(i, target.getRank() + (target.getFile() - i))); + } + + return path; + } +} \ No newline at end of file diff --git a/src/main/java/chess/domain/move/direction/RightDownStrategy.java b/src/main/java/chess/domain/move/direction/RightDownStrategy.java new file mode 100644 index 00000000000..abde87be180 --- /dev/null +++ b/src/main/java/chess/domain/move/direction/RightDownStrategy.java @@ -0,0 +1,20 @@ +package chess.domain.move.direction; + +import chess.domain.position.Position; + +import java.util.ArrayList; +import java.util.List; + +public class RightDownStrategy implements DirectionStrategy { + + @Override + public List find(Position source, Position target) { + List path = new ArrayList<>(); + + for (int i = target.getFile() - 1 ; i > source.getFile() ; i--) { + path.add(Position.of(i, target.getRank() - (target.getFile() - i))); + } + + return path; + } +} diff --git a/src/main/java/chess/domain/move/direction/RightStrategy.java b/src/main/java/chess/domain/move/direction/RightStrategy.java new file mode 100644 index 00000000000..f07bdf3360b --- /dev/null +++ b/src/main/java/chess/domain/move/direction/RightStrategy.java @@ -0,0 +1,18 @@ +package chess.domain.move.direction; + +import chess.domain.position.Position; + +import java.util.ArrayList; +import java.util.List; + +public class RightStrategy implements DirectionStrategy { + @Override + public List find(Position source, Position target) { + List path = new ArrayList<>(); + + for (int i = target.getFile() - 1; i > source.getFile(); i--) { + path.add(Position.of(i, source.getRank())); + } + return path; + } +} \ No newline at end of file diff --git a/src/main/java/chess/domain/move/direction/RightUpStrategy.java b/src/main/java/chess/domain/move/direction/RightUpStrategy.java new file mode 100644 index 00000000000..bd2c6afcd4f --- /dev/null +++ b/src/main/java/chess/domain/move/direction/RightUpStrategy.java @@ -0,0 +1,20 @@ +package chess.domain.move.direction; + +import chess.domain.position.Position; + +import java.util.ArrayList; +import java.util.List; + +public class RightUpStrategy implements DirectionStrategy { + + @Override + public List find(Position source, Position target) { + List path = new ArrayList<>(); + + for (int i = target.getFile() - 1 ; i > source.getFile() ; i--) { + path.add(Position.of(i, target.getRank() - (target.getFile() - i))); + } + + return path; + } +} diff --git a/src/main/java/chess/domain/piece/Piece.java b/src/main/java/chess/domain/piece/Piece.java index 5286a31b705..672aecf7216 100644 --- a/src/main/java/chess/domain/piece/Piece.java +++ b/src/main/java/chess/domain/piece/Piece.java @@ -6,12 +6,10 @@ public class Piece { private final PieceType pieceType; private final Team team; -// private final MoveStrategy moveStrategy; public Piece(final PieceType pieceType, final Team team) { this.pieceType = pieceType; this.team = team; -// this.moveStrategy = MoveStrategyFactory.create(pieceType, team); } public String toSymbol() { diff --git a/src/main/java/chess/domain/position/File.java b/src/main/java/chess/domain/position/File.java index 0a856960b02..51666ff95e8 100644 --- a/src/main/java/chess/domain/position/File.java +++ b/src/main/java/chess/domain/position/File.java @@ -3,19 +3,21 @@ import java.util.Arrays; public enum File { - A('a'), - B('b'), - C('c'), - D('d'), - E('e'), - F('f'), - G('g'), - H('h'); + A('a', 1), + B('b', 2), + C('c', 3), + D('d', 4), + E('e', 5), + F('f', 6), + G('g', 7), + H('h', 8); private final char symbol; + private final int number; - File(char symbol) { + File(char symbol, int number) { this.symbol = symbol; + this.number = number; } public static File of(String file) { @@ -27,11 +29,15 @@ public static File of(String file) { public static File of(int file) { return Arrays.stream(values()) - .filter(f -> f.symbol == (char) file) + .filter(f -> f.number == file) .findFirst() .orElseThrow(() -> new IllegalArgumentException("잘못된 x 좌표값을 입력하였습니다.")); } + public int getNumber() { + return number; + } + public int getSymbol() { return this.symbol; } diff --git a/src/main/java/chess/domain/position/Position.java b/src/main/java/chess/domain/position/Position.java index 29520ae3f02..8ca674b00fa 100644 --- a/src/main/java/chess/domain/position/Position.java +++ b/src/main/java/chess/domain/position/Position.java @@ -49,8 +49,6 @@ public static Position of(final File file, final Rank rank) { } public static Position of(final int fileSymbol, final int rankSymbol) { - - return findPosition(File.of(fileSymbol), Rank.of(rankSymbol)); } @@ -72,7 +70,7 @@ public int calculateRankGap(Position target) { } public int getFile() { - return this.file.getSymbol(); + return this.file.getNumber(); } public int getRank() { diff --git a/src/main/java/chess/view/InputView.java b/src/main/java/chess/view/InputView.java index 6d6ef517950..108539edd2a 100644 --- a/src/main/java/chess/view/InputView.java +++ b/src/main/java/chess/view/InputView.java @@ -1,6 +1,8 @@ package chess.view; public interface InputView { + boolean askChessRun(); + String askMove(); } From c6fd4f6dc2bc927b873ab53c6d530a91897bb67a Mon Sep 17 00:00:00 2001 From: giantim Date: Thu, 26 Mar 2020 16:26:21 +0900 Subject: [PATCH 10/29] =?UTF-8?q?feat:=202=EB=8B=A8=EA=B3=84=20=EA=B5=AC?= =?UTF-8?q?=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/ChessApplication.java | 2 +- .../chess/controller/ChessController.java | 32 ++++++++++++++----- src/main/java/chess/domain/board/Board.java | 3 +- .../chess/domain/move/KingMoveStrategy.java | 1 - .../java/chess/domain/move/MoveStrategy.java | 2 +- .../chess/domain/move/RookMoveStrategy.java | 5 +-- .../move/direction/LeftDownStrategy.java | 2 +- .../domain/move/direction/LeftUpStrategy.java | 3 +- .../move/direction/RightDownStrategy.java | 2 +- .../move/direction/RightUpStrategy.java | 2 +- .../domain/move/direction/UpStrategy.java | 4 +-- .../java/chess/domain/position/Position.java | 3 +- src/main/java/chess/domain/position/Rank.java | 5 +++ 13 files changed, 40 insertions(+), 26 deletions(-) diff --git a/src/main/java/chess/ChessApplication.java b/src/main/java/chess/ChessApplication.java index f70d30b2b5f..ac637cc3938 100644 --- a/src/main/java/chess/ChessApplication.java +++ b/src/main/java/chess/ChessApplication.java @@ -5,6 +5,6 @@ public class ChessApplication { public static void main(String[] args) { - ChessController.run(); + ChessController.start(); } } \ No newline at end of file diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index 6590998b01b..6bc65e1e79e 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -14,15 +14,31 @@ public class ChessController { private static InputView inputView = new ConsoleInputView(); private static OutputView outputView = new ConsoleOutputView(); - public static void run() { + public static void start() { if (inputView.askChessRun()) { - ChessRunner chessRunner = new ChessRunner(); - printInitialize(chessRunner.getBoard()); - String[] moveSource = inputView.askMove().split(" "); - String sourcePosition = moveSource[1]; - String targetPosition = moveSource[2]; - chessRunner.update(sourcePosition, targetPosition); - printInitialize(chessRunner.getBoard()); + run(); + } + } + + + public static void run() { + ChessRunner chessRunner = new ChessRunner(); + printInitialize(chessRunner.getBoard()); + boolean moveFlag = true; + + while (moveFlag) { + try { + String[] moveSource = inputView.askMove().split(" "); + if (moveSource[0].toUpperCase() == "END") { + break; + } + String sourcePosition = moveSource[1]; + String targetPosition = moveSource[2]; + chessRunner.update(sourcePosition, targetPosition); + printInitialize(chessRunner.getBoard()); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } } } diff --git a/src/main/java/chess/domain/board/Board.java b/src/main/java/chess/domain/board/Board.java index e98ce9021fc..1df9825a933 100644 --- a/src/main/java/chess/domain/board/Board.java +++ b/src/main/java/chess/domain/board/Board.java @@ -1,7 +1,6 @@ package chess.domain.board; import chess.domain.piece.Piece; -import chess.domain.piece.Team; import chess.domain.position.Position; import java.util.Collections; @@ -31,7 +30,7 @@ public void updateBoard(Position sourcePosition, Position targetPosition, Piece } public boolean isEmpty(final Position position) { - return this.board.containsKey(position); + return !this.board.containsKey(position); } public Piece getPiece(final Position position) { diff --git a/src/main/java/chess/domain/move/KingMoveStrategy.java b/src/main/java/chess/domain/move/KingMoveStrategy.java index bc816329df6..c4e9a086426 100644 --- a/src/main/java/chess/domain/move/KingMoveStrategy.java +++ b/src/main/java/chess/domain/move/KingMoveStrategy.java @@ -1,7 +1,6 @@ package chess.domain.move; import chess.domain.board.Board; -import chess.domain.piece.Piece; import chess.domain.position.Position; public class KingMoveStrategy extends MoveStrategy { diff --git a/src/main/java/chess/domain/move/MoveStrategy.java b/src/main/java/chess/domain/move/MoveStrategy.java index 77524596c9e..bb43e5055c3 100644 --- a/src/main/java/chess/domain/move/MoveStrategy.java +++ b/src/main/java/chess/domain/move/MoveStrategy.java @@ -16,7 +16,7 @@ protected boolean isSamePosition(Position source, Position target) { public abstract boolean movable(Position source, Position target, Board board); protected boolean checkObstacle(Position source, Position target, Board board) { - DirectionStrategy directionStrategy= PathFinder.find(source, target); + DirectionStrategy directionStrategy = PathFinder.find(source, target); List path = directionStrategy.find(source, target); for (Position position : path) { diff --git a/src/main/java/chess/domain/move/RookMoveStrategy.java b/src/main/java/chess/domain/move/RookMoveStrategy.java index d9db390d72d..67ce216c581 100644 --- a/src/main/java/chess/domain/move/RookMoveStrategy.java +++ b/src/main/java/chess/domain/move/RookMoveStrategy.java @@ -1,11 +1,8 @@ package chess.domain.move; import chess.domain.board.Board; -import chess.domain.move.direction.DirectionStrategy; import chess.domain.position.Position; -import java.util.List; - public class RookMoveStrategy extends MoveStrategy { @Override public boolean movable(Position source, Position target, Board board) { @@ -16,7 +13,7 @@ public boolean movable(Position source, Position target, Board board) { int fileGap = Math.abs(source.calculateFileGap(target)); int rankGap = Math.abs(source.calculateRankGap(target)); - return (fileGap == 0 && rankGap > 0) + return ((fileGap > 0 && rankGap == 0) || (fileGap == 0 && rankGap > 0)) && checkObstacle(source, target, board) && checkTarget(source, target, board); } diff --git a/src/main/java/chess/domain/move/direction/LeftDownStrategy.java b/src/main/java/chess/domain/move/direction/LeftDownStrategy.java index 29dd121a889..a2950d3d9b3 100644 --- a/src/main/java/chess/domain/move/direction/LeftDownStrategy.java +++ b/src/main/java/chess/domain/move/direction/LeftDownStrategy.java @@ -11,7 +11,7 @@ public class LeftDownStrategy implements DirectionStrategy { public List find(Position source, Position target) { List path = new ArrayList<>(); - for (int i = target.getFile() + 1 ; i < source.getFile() ; i++) { + for (int i = target.getFile() + 1; i < source.getFile(); i++) { path.add(Position.of(i, target.getRank() - (target.getFile() - i))); } diff --git a/src/main/java/chess/domain/move/direction/LeftUpStrategy.java b/src/main/java/chess/domain/move/direction/LeftUpStrategy.java index 30e0511bbd5..f2a8719eaa3 100644 --- a/src/main/java/chess/domain/move/direction/LeftUpStrategy.java +++ b/src/main/java/chess/domain/move/direction/LeftUpStrategy.java @@ -1,6 +1,5 @@ package chess.domain.move.direction; -import chess.domain.position.File; import chess.domain.position.Position; import java.util.ArrayList; @@ -11,7 +10,7 @@ public class LeftUpStrategy implements DirectionStrategy { public List find(Position source, Position target) { List path = new ArrayList<>(); - for (int i = target.getFile() + 1 ; i < source.getFile() ; i++) { + for (int i = target.getFile() + 1; i < source.getFile(); i++) { path.add(Position.of(i, target.getRank() + (target.getFile() - i))); } diff --git a/src/main/java/chess/domain/move/direction/RightDownStrategy.java b/src/main/java/chess/domain/move/direction/RightDownStrategy.java index abde87be180..ce28c51645f 100644 --- a/src/main/java/chess/domain/move/direction/RightDownStrategy.java +++ b/src/main/java/chess/domain/move/direction/RightDownStrategy.java @@ -11,7 +11,7 @@ public class RightDownStrategy implements DirectionStrategy { public List find(Position source, Position target) { List path = new ArrayList<>(); - for (int i = target.getFile() - 1 ; i > source.getFile() ; i--) { + for (int i = target.getFile() - 1; i > source.getFile(); i--) { path.add(Position.of(i, target.getRank() - (target.getFile() - i))); } diff --git a/src/main/java/chess/domain/move/direction/RightUpStrategy.java b/src/main/java/chess/domain/move/direction/RightUpStrategy.java index bd2c6afcd4f..b19bd61bd58 100644 --- a/src/main/java/chess/domain/move/direction/RightUpStrategy.java +++ b/src/main/java/chess/domain/move/direction/RightUpStrategy.java @@ -11,7 +11,7 @@ public class RightUpStrategy implements DirectionStrategy { public List find(Position source, Position target) { List path = new ArrayList<>(); - for (int i = target.getFile() - 1 ; i > source.getFile() ; i--) { + for (int i = target.getFile() - 1; i > source.getFile(); i--) { path.add(Position.of(i, target.getRank() - (target.getFile() - i))); } diff --git a/src/main/java/chess/domain/move/direction/UpStrategy.java b/src/main/java/chess/domain/move/direction/UpStrategy.java index 3fd2319d9e8..1bcf3de6da6 100644 --- a/src/main/java/chess/domain/move/direction/UpStrategy.java +++ b/src/main/java/chess/domain/move/direction/UpStrategy.java @@ -11,8 +11,8 @@ public List find(Position source, Position target) { List path = new ArrayList<>(); for (int i = target.getRank() - 1; i > source.getRank(); i--) { - path.add(Position.of(source.getFile(), i)); - } + path.add(Position.of(source.getFile(), i)); + } return path; } } \ No newline at end of file diff --git a/src/main/java/chess/domain/position/Position.java b/src/main/java/chess/domain/position/Position.java index 8ca674b00fa..ac8a76b63e4 100644 --- a/src/main/java/chess/domain/position/Position.java +++ b/src/main/java/chess/domain/position/Position.java @@ -65,8 +65,7 @@ public int calculateFileGap(Position target) { } public int calculateRankGap(Position target) { - int rankGap = this.rank.compareTo(target.rank); - return rankGap; + return this.rank.getDifference(target.rank); } public int getFile() { diff --git a/src/main/java/chess/domain/position/Rank.java b/src/main/java/chess/domain/position/Rank.java index c1cbd0e889c..86f966f7544 100644 --- a/src/main/java/chess/domain/position/Rank.java +++ b/src/main/java/chess/domain/position/Rank.java @@ -35,4 +35,9 @@ public static Rank of(int rank) { public int getSymbol() { return this.symbol; } + + + public int getDifference(Rank rank) { + return this.symbol - rank.symbol; + } } From b757656f3fc887817f142625fad305c50b8e176d Mon Sep 17 00:00:00 2001 From: giantim Date: Thu, 26 Mar 2020 16:46:54 +0900 Subject: [PATCH 11/29] =?UTF-8?q?feat:=20=EC=99=95=EC=9D=B4=20=EC=A3=BD?= =?UTF-8?q?=EC=97=88=EC=9D=84=20=EB=95=8C=20=EC=8A=B9=EB=A6=AC=ED=95=9C=20?= =?UTF-8?q?=ED=8C=80=20=EC=B6=9C=EB=A0=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chess/controller/ChessController.java | 9 +++++++ src/main/java/chess/domain/ChessRunner.java | 4 +++ src/main/java/chess/domain/board/Board.java | 25 +++++++++++++++++++ src/main/java/chess/domain/piece/Piece.java | 8 ++++++ .../java/chess/domain/piece/PieceType.java | 4 +++ .../java/chess/view/ConsoleOutputView.java | 7 ++++++ src/main/java/chess/view/OutputView.java | 4 +++ 7 files changed, 61 insertions(+) diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index 6bc65e1e79e..7ae66f09a21 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -36,12 +36,21 @@ public static void run() { String targetPosition = moveSource[2]; chessRunner.update(sourcePosition, targetPosition); printInitialize(chessRunner.getBoard()); + if (checkWinner(chessRunner)) continue; + } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } } + private static boolean checkWinner(ChessRunner chessRunner) { + if (chessRunner.checkWinner() != null) { + outputView.printWinner(chessRunner.checkWinner()); + } + return true; + } + private static void printInitialize(Board board) { BoardDto boardDto = new BoardDto(board.parse()); PositionDto positionDto = new PositionDto(Position.getPositions()); diff --git a/src/main/java/chess/domain/ChessRunner.java b/src/main/java/chess/domain/ChessRunner.java index 478814ed72b..b1f462e2d01 100644 --- a/src/main/java/chess/domain/ChessRunner.java +++ b/src/main/java/chess/domain/ChessRunner.java @@ -37,6 +37,10 @@ private void changeTurn() { this.currentTeam = Team.changeTurn(this.currentTeam); } + public Team checkWinner() { + return this.board.checkWinner(); + } + public Board getBoard() { return this.board; } diff --git a/src/main/java/chess/domain/board/Board.java b/src/main/java/chess/domain/board/Board.java index 1df9825a933..d2983e520b6 100644 --- a/src/main/java/chess/domain/board/Board.java +++ b/src/main/java/chess/domain/board/Board.java @@ -1,6 +1,7 @@ package chess.domain.board; import chess.domain.piece.Piece; +import chess.domain.piece.Team; import chess.domain.position.Position; import java.util.Collections; @@ -29,6 +30,30 @@ public void updateBoard(Position sourcePosition, Position targetPosition, Piece this.board.remove(sourcePosition); } + public Team checkWinner() { + if (checkWhiteKing() && !checkBlackKing()) { + return Team.WHITE; + } + if (!checkWhiteKing() && checkBlackKing()) { + return Team.BLACK; + } + return null; + } + + private boolean checkWhiteKing() { + for (Piece piece : board.values()) { + if (piece.isWhiteKing()) return true; + } + return false; + } + + private boolean checkBlackKing() { + for (Piece piece : board.values()) { + if (piece.isBlackKing()) return true; + } + return false; + } + public boolean isEmpty(final Position position) { return !this.board.containsKey(position); } diff --git a/src/main/java/chess/domain/piece/Piece.java b/src/main/java/chess/domain/piece/Piece.java index 672aecf7216..7ca77251f52 100644 --- a/src/main/java/chess/domain/piece/Piece.java +++ b/src/main/java/chess/domain/piece/Piece.java @@ -27,4 +27,12 @@ public boolean isEnemy(Piece targetPiece) { public Team getTeam() { return this.team; } + + public boolean isWhiteKing() { + return this.pieceType.isKing() && this.team.isWhite(); + } + + public boolean isBlackKing() { + return this.pieceType.isKing() && !this.team.isWhite(); + } } diff --git a/src/main/java/chess/domain/piece/PieceType.java b/src/main/java/chess/domain/piece/PieceType.java index f3e742e3247..89814cbccb3 100644 --- a/src/main/java/chess/domain/piece/PieceType.java +++ b/src/main/java/chess/domain/piece/PieceType.java @@ -29,4 +29,8 @@ public String getSymbol() { public boolean move(Position source, Position target, Board board) { return this.moveStrategy.movable(source, target, board); } + + public boolean isKing() { + return this == KING; + } } \ No newline at end of file diff --git a/src/main/java/chess/view/ConsoleOutputView.java b/src/main/java/chess/view/ConsoleOutputView.java index d9208378aae..641b002edec 100644 --- a/src/main/java/chess/view/ConsoleOutputView.java +++ b/src/main/java/chess/view/ConsoleOutputView.java @@ -1,5 +1,7 @@ package chess.view; +import chess.domain.piece.Team; + import java.util.List; import java.util.Map; @@ -28,4 +30,9 @@ private String printPiece(String piece) { } return piece; } + + @Override + public void printWinner(Team team) { + System.out.println(String.format("%s 팀이 이겼습니다.", team.name())); + } } diff --git a/src/main/java/chess/view/OutputView.java b/src/main/java/chess/view/OutputView.java index 578a232713f..1678ba6d52e 100644 --- a/src/main/java/chess/view/OutputView.java +++ b/src/main/java/chess/view/OutputView.java @@ -1,8 +1,12 @@ package chess.view; +import chess.domain.piece.Team; + import java.util.List; import java.util.Map; public interface OutputView { void printBoard(List positions, Map board); + + void printWinner(Team team); } From 202d59045ef399e62f01b367328de301fab4fbe4 Mon Sep 17 00:00:00 2001 From: giantim Date: Thu, 26 Mar 2020 16:47:44 +0900 Subject: [PATCH 12/29] =?UTF-8?q?feat:=20=EC=99=95=EC=9D=B4=20=EC=A3=BD?= =?UTF-8?q?=EC=97=88=EC=9D=84=20=EB=95=8C=20=EA=B2=8C=EC=9E=84=20=EC=A2=85?= =?UTF-8?q?=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/controller/ChessController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index 7ae66f09a21..b5922ae1d82 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -36,7 +36,7 @@ public static void run() { String targetPosition = moveSource[2]; chessRunner.update(sourcePosition, targetPosition); printInitialize(chessRunner.getBoard()); - if (checkWinner(chessRunner)) continue; + if (!checkWinner(chessRunner)) break; } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); From 622ee0a626f2d50e27bb42e6b500bc56584279dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=98=88=EB=B9=88?= Date: Thu, 26 Mar 2020 17:16:44 +0900 Subject: [PATCH 13/29] =?UTF-8?q?feat:=20status=20=EB=AA=85=EB=A0=B9?= =?UTF-8?q?=EC=96=B4=20=EC=9E=85=EB=A0=A5=20=EC=8B=9C=20=EC=A0=90=EC=88=98?= =?UTF-8?q?=20=EA=B3=84=EC=82=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/controller/ChessController.java | 9 ++++++--- src/main/java/chess/domain/ChessRunner.java | 11 ++++++++--- src/main/java/chess/domain/board/Board.java | 10 ++++++++++ src/main/java/chess/domain/piece/Piece.java | 12 ++++++++---- src/main/java/chess/domain/piece/PieceType.java | 4 ++++ src/main/java/chess/view/ConsoleInputView.java | 6 +++--- src/main/java/chess/view/ConsoleOutputView.java | 5 +++++ src/main/java/chess/view/InputView.java | 2 +- src/main/java/chess/view/OutputView.java | 2 ++ 9 files changed, 47 insertions(+), 14 deletions(-) diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index b5922ae1d82..888d6e8da30 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -20,7 +20,6 @@ public static void start() { } } - public static void run() { ChessRunner chessRunner = new ChessRunner(); printInitialize(chessRunner.getBoard()); @@ -28,10 +27,14 @@ public static void run() { while (moveFlag) { try { - String[] moveSource = inputView.askMove().split(" "); - if (moveSource[0].toUpperCase() == "END") { + String[] moveSource = inputView.askMoveOrStatus().split(" "); + if (moveSource[0].toUpperCase().equals("END")) { break; } + if (moveSource[0].toUpperCase().equals("STATUS")) { + outputView.printStatus(chessRunner.calculateScore(), chessRunner.getCurrentTeam()); + continue; + } String sourcePosition = moveSource[1]; String targetPosition = moveSource[2]; chessRunner.update(sourcePosition, targetPosition); diff --git a/src/main/java/chess/domain/ChessRunner.java b/src/main/java/chess/domain/ChessRunner.java index b1f462e2d01..73c1d1f6ee9 100644 --- a/src/main/java/chess/domain/ChessRunner.java +++ b/src/main/java/chess/domain/ChessRunner.java @@ -26,11 +26,8 @@ public void update(String source, String target) { if (!(selectedPiece.move(sourcePosition, targetPosition, board))) { throw new IllegalArgumentException("이동할 수 없는 곳입니다."); } - this.board.updateBoard(sourcePosition, targetPosition, selectedPiece); - changeTurn(); - } private void changeTurn() { @@ -41,6 +38,14 @@ public Team checkWinner() { return this.board.checkWinner(); } + public double calculateScore() { + return board.calculateScore(currentTeam); + } + + public Team getCurrentTeam() { + return currentTeam; + } + public Board getBoard() { return this.board; } diff --git a/src/main/java/chess/domain/board/Board.java b/src/main/java/chess/domain/board/Board.java index d2983e520b6..13f0666a432 100644 --- a/src/main/java/chess/domain/board/Board.java +++ b/src/main/java/chess/domain/board/Board.java @@ -61,4 +61,14 @@ public boolean isEmpty(final Position position) { public Piece getPiece(final Position position) { return this.board.get(position); } + + public double calculateScore(Team team) { + double score = 0; + for (Piece piece : board.values()) { + if (piece.getTeam() == team) { + score += piece.getScore(); + } + } + return score; + } } \ No newline at end of file diff --git a/src/main/java/chess/domain/piece/Piece.java b/src/main/java/chess/domain/piece/Piece.java index 7ca77251f52..ade246fb0e3 100644 --- a/src/main/java/chess/domain/piece/Piece.java +++ b/src/main/java/chess/domain/piece/Piece.java @@ -24,10 +24,6 @@ public boolean isEnemy(Piece targetPiece) { return this.team.isEnemy(targetPiece.getTeam()); } - public Team getTeam() { - return this.team; - } - public boolean isWhiteKing() { return this.pieceType.isKing() && this.team.isWhite(); } @@ -35,4 +31,12 @@ public boolean isWhiteKing() { public boolean isBlackKing() { return this.pieceType.isKing() && !this.team.isWhite(); } + + public Team getTeam() { + return this.team; + } + + public double getScore() { + return this.pieceType.getScore(); + } } diff --git a/src/main/java/chess/domain/piece/PieceType.java b/src/main/java/chess/domain/piece/PieceType.java index 89814cbccb3..8bf41e1ada4 100644 --- a/src/main/java/chess/domain/piece/PieceType.java +++ b/src/main/java/chess/domain/piece/PieceType.java @@ -33,4 +33,8 @@ public boolean move(Position source, Position target, Board board) { public boolean isKing() { return this == KING; } + + public double getScore() { + return score; + } } \ No newline at end of file diff --git a/src/main/java/chess/view/ConsoleInputView.java b/src/main/java/chess/view/ConsoleInputView.java index 3dc45472fba..83347cc5bd3 100644 --- a/src/main/java/chess/view/ConsoleInputView.java +++ b/src/main/java/chess/view/ConsoleInputView.java @@ -37,19 +37,19 @@ private boolean runFlag(String input) { } @Override - public String askMove() { + public String askMoveOrStatus() { try { String input = SCANNER.nextLine(); validateMove(input); return input; } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); - return askMove(); + return askMoveOrStatus(); } } private static void validateMove(String input) { - if (!input.contains("move")) { + if (!input.contains("move") && !input.equals("status") && !input.equals("end")) { throw new IllegalArgumentException("잘못된 명령어를 입력하였습니다."); } } diff --git a/src/main/java/chess/view/ConsoleOutputView.java b/src/main/java/chess/view/ConsoleOutputView.java index 641b002edec..b6326a5d503 100644 --- a/src/main/java/chess/view/ConsoleOutputView.java +++ b/src/main/java/chess/view/ConsoleOutputView.java @@ -35,4 +35,9 @@ private String printPiece(String piece) { public void printWinner(Team team) { System.out.println(String.format("%s 팀이 이겼습니다.", team.name())); } + + @Override + public void printStatus(double calculateScore, Team team) { + System.out.println(String.format("%s 팀의 점수는 %.1f 점입니다.", team.name(), calculateScore)); + } } diff --git a/src/main/java/chess/view/InputView.java b/src/main/java/chess/view/InputView.java index 108539edd2a..01c2fb9df8f 100644 --- a/src/main/java/chess/view/InputView.java +++ b/src/main/java/chess/view/InputView.java @@ -4,5 +4,5 @@ public interface InputView { boolean askChessRun(); - String askMove(); + String askMoveOrStatus(); } diff --git a/src/main/java/chess/view/OutputView.java b/src/main/java/chess/view/OutputView.java index 1678ba6d52e..99cf6959ee1 100644 --- a/src/main/java/chess/view/OutputView.java +++ b/src/main/java/chess/view/OutputView.java @@ -9,4 +9,6 @@ public interface OutputView { void printBoard(List positions, Map board); void printWinner(Team team); + + void printStatus(double calculateScore, Team team); } From 6a947619329fdeec0cb45cce56c47037f8a58ca2 Mon Sep 17 00:00:00 2001 From: giantim Date: Thu, 26 Mar 2020 17:35:55 +0900 Subject: [PATCH 14/29] =?UTF-8?q?feat:=203=EB=8B=A8=EA=B3=84=20=EA=B8=B0?= =?UTF-8?q?=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 --- src/main/java/chess/domain/board/Board.java | 12 ++++++++++++ src/main/java/chess/domain/piece/Piece.java | 8 ++++++++ src/main/java/chess/domain/piece/PieceType.java | 4 ++++ 3 files changed, 24 insertions(+) diff --git a/src/main/java/chess/domain/board/Board.java b/src/main/java/chess/domain/board/Board.java index 13f0666a432..39ebb6c7b8a 100644 --- a/src/main/java/chess/domain/board/Board.java +++ b/src/main/java/chess/domain/board/Board.java @@ -2,10 +2,12 @@ import chess.domain.piece.Piece; import chess.domain.piece.Team; +import chess.domain.position.File; import chess.domain.position.Position; import java.util.Collections; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -69,6 +71,16 @@ public double calculateScore(Team team) { score += piece.getScore(); } } + + for (File file : File.values()) { + List> sameFile = this.board.entrySet().stream() + .filter(entry -> File.of(entry.getKey().getFile()).equals(file)) + .filter(entry -> entry.getValue().isPawn() && !entry.getValue().isEnemy(team)) + .collect(Collectors.toList()); + if (sameFile.size() > 1) { + score -= sameFile.size() * 0.5; + } + } return score; } } \ No newline at end of file diff --git a/src/main/java/chess/domain/piece/Piece.java b/src/main/java/chess/domain/piece/Piece.java index ade246fb0e3..46befc3474c 100644 --- a/src/main/java/chess/domain/piece/Piece.java +++ b/src/main/java/chess/domain/piece/Piece.java @@ -24,6 +24,10 @@ public boolean isEnemy(Piece targetPiece) { return this.team.isEnemy(targetPiece.getTeam()); } + public boolean isEnemy(Team team) { + return this.team.isEnemy(team); + } + public boolean isWhiteKing() { return this.pieceType.isKing() && this.team.isWhite(); } @@ -39,4 +43,8 @@ public Team getTeam() { public double getScore() { return this.pieceType.getScore(); } + + public boolean isPawn() { + return this.pieceType.isPawn(); + } } diff --git a/src/main/java/chess/domain/piece/PieceType.java b/src/main/java/chess/domain/piece/PieceType.java index 8bf41e1ada4..c9594930798 100644 --- a/src/main/java/chess/domain/piece/PieceType.java +++ b/src/main/java/chess/domain/piece/PieceType.java @@ -37,4 +37,8 @@ public boolean isKing() { public double getScore() { return score; } + + public boolean isPawn() { + return this == PAWN; + } } \ No newline at end of file From fdc9cfa1a295936c35765e47f5941879eb938a78 Mon Sep 17 00:00:00 2001 From: giantim Date: Thu, 26 Mar 2020 17:40:07 +0900 Subject: [PATCH 15/29] =?UTF-8?q?doc:=20README=20=EC=97=85=EB=8D=B0?= =?UTF-8?q?=EC=9D=B4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ef5dd275132..0c1464ff026 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,18 @@ ## 기능 요구 사항 1단계 - - [ ] 명령어를 입력 받는다(start, end) - - [ ] (예외) start, end 외의 명령어가 입력된 경우 다시 명령어를 입력 받는다 - - [ ] start 를 입력 시 체스판을 초기화 한다 - - [ ] end 를 입력 시 게임을 종료한다 + - [x] 명령어를 입력 받는다(start, end) + - [x] (예외) start, end 외의 명령어가 입력된 경우 다시 명령어를 입력 받는다 + - [x] start 를 입력 시 체스판을 초기화 한다 + - [x] end 를 입력 시 게임을 종료한다 + + 2단계 + - [x] 체스 말 규칙에 따라 말을 이동한다 + - [x] 폰은 시작 위치에서 2칸 이동이 가능하고 시작 위치가 아닐 때 대각선의 적을 잡을 수 있다 + - [x] `move source위치 target위치` 명령어로 말을 움직인다 + + 3단계 + - [x] 왕을 잡으면 게임이 종료된다 + - [x] `status` 명령어를 입력하면 현재 남아있는 말의 점수를 구할 수 있다 + - [x] 한 번에 한 쪽의 점수만 계산한다 + - [x] 같은 세로줄에 같은 색의 폰이 있는 경우 1점이 아닌 0.5점을 준다 From fb4d0af351e33e203c6a5583892c1b62c9b6cf06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=98=88=EB=B9=88?= Date: Thu, 26 Mar 2020 20:36:06 +0900 Subject: [PATCH 16/29] =?UTF-8?q?refactor:=20=EC=84=B8=EB=B6=80=20?= =?UTF-8?q?=EB=84=A4=EC=9D=B4=EB=B0=8D=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chess/controller/ChessController.java | 17 ++++++++------- .../chess/controller/dto/PositionDto.java | 2 +- src/main/java/chess/domain/ChessRunner.java | 18 +++++++++------- src/main/java/chess/domain/board/Board.java | 21 ++++++++++++------- ...der.java => DirectionStrategyFactory.java} | 2 +- .../java/chess/domain/move/MoveStrategy.java | 6 +++--- src/main/java/chess/domain/piece/Piece.java | 18 ++++++++-------- .../java/chess/domain/piece/PieceType.java | 14 ++++++------- src/main/java/chess/domain/piece/Team.java | 8 +++---- src/main/java/chess/domain/position/File.java | 4 ---- src/main/java/chess/domain/position/Rank.java | 3 +-- .../java/chess/view/ConsoleInputView.java | 9 +++----- 12 files changed, 64 insertions(+), 58 deletions(-) rename src/main/java/chess/domain/move/{PathFinder.java => DirectionStrategyFactory.java} (96%) diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index 888d6e8da30..7488488f82d 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -4,6 +4,7 @@ import chess.controller.dto.PositionDto; import chess.domain.ChessRunner; import chess.domain.board.Board; +import chess.domain.piece.Team; import chess.domain.position.Position; import chess.view.ConsoleInputView; import chess.view.ConsoleOutputView; @@ -22,7 +23,7 @@ public static void start() { public static void run() { ChessRunner chessRunner = new ChessRunner(); - printInitialize(chessRunner.getBoard()); + printBoard(chessRunner.getBoard()); boolean moveFlag = true; while (moveFlag) { @@ -38,8 +39,8 @@ public static void run() { String sourcePosition = moveSource[1]; String targetPosition = moveSource[2]; chessRunner.update(sourcePosition, targetPosition); - printInitialize(chessRunner.getBoard()); - if (!checkWinner(chessRunner)) break; + printBoard(chessRunner.getBoard()); + if (!findWinner(chessRunner)) break; } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); @@ -47,14 +48,16 @@ public static void run() { } } - private static boolean checkWinner(ChessRunner chessRunner) { - if (chessRunner.checkWinner() != null) { - outputView.printWinner(chessRunner.checkWinner()); + private static boolean findWinner(ChessRunner chessRunner) { + Team winner = chessRunner.findWinner(); + if (winner != null) { + outputView.printWinner(winner); + return false; } return true; } - private static void printInitialize(Board board) { + private static void printBoard(Board board) { BoardDto boardDto = new BoardDto(board.parse()); PositionDto positionDto = new PositionDto(Position.getPositions()); outputView.printBoard(positionDto.getPositions(), boardDto.get()); diff --git a/src/main/java/chess/controller/dto/PositionDto.java b/src/main/java/chess/controller/dto/PositionDto.java index db5875990fe..4083a2f2444 100644 --- a/src/main/java/chess/controller/dto/PositionDto.java +++ b/src/main/java/chess/controller/dto/PositionDto.java @@ -13,4 +13,4 @@ public PositionDto(final List positions) { public List getPositions() { return Collections.unmodifiableList(positions); } -} +} \ No newline at end of file diff --git a/src/main/java/chess/domain/ChessRunner.java b/src/main/java/chess/domain/ChessRunner.java index 73c1d1f6ee9..9adfae4119f 100644 --- a/src/main/java/chess/domain/ChessRunner.java +++ b/src/main/java/chess/domain/ChessRunner.java @@ -19,22 +19,26 @@ public void update(String source, String target) { Position targetPosition = Position.of(target); Piece selectedPiece = this.board.getPiece(sourcePosition); - if ((currentTeam.isEnemy(selectedPiece.getTeam()))) { + if ((currentTeam.isSameTeamWith(selectedPiece.getTeam()))) { throw new IllegalArgumentException("현재 차례가 아닙니다."); } - if (!(selectedPiece.move(sourcePosition, targetPosition, board))) { + if (!(selectedPiece.movable(sourcePosition, targetPosition, board))) { throw new IllegalArgumentException("이동할 수 없는 곳입니다."); } - this.board.updateBoard(sourcePosition, targetPosition, selectedPiece); - changeTurn(); + updateBoard(sourcePosition, targetPosition); + changeTeam(); } - private void changeTurn() { - this.currentTeam = Team.changeTurn(this.currentTeam); + private void updateBoard(Position sourcePosition, Position targetPosition) { + this.board.updateBoard(sourcePosition, targetPosition); } - public Team checkWinner() { + private void changeTeam() { + this.currentTeam = Team.changeTeam(this.currentTeam); + } + + public Team findWinner() { return this.board.checkWinner(); } diff --git a/src/main/java/chess/domain/board/Board.java b/src/main/java/chess/domain/board/Board.java index 39ebb6c7b8a..0c5c21b5034 100644 --- a/src/main/java/chess/domain/board/Board.java +++ b/src/main/java/chess/domain/board/Board.java @@ -27,7 +27,8 @@ public Map parse() { return Collections.unmodifiableMap(parseResult); } - public void updateBoard(Position sourcePosition, Position targetPosition, Piece selectedPiece) { + public void updateBoard(Position sourcePosition, Position targetPosition) { + Piece selectedPiece = this.board.get(sourcePosition); this.board.put(targetPosition, selectedPiece); this.board.remove(sourcePosition); } @@ -65,18 +66,24 @@ public Piece getPiece(final Position position) { } public double calculateScore(Team team) { - double score = 0; - for (Piece piece : board.values()) { - if (piece.getTeam() == team) { - score += piece.getScore(); - } - } + double totalScore = calculateTotalScore(team); + return calculatePawnScore(team, totalScore); + } + private double calculateTotalScore(Team team) { + return board.values().stream() + .filter(piece -> team.isSameTeamWith(piece.getTeam())) + .mapToDouble(Piece::getScore) + .sum(); + } + + private double calculatePawnScore(Team team, double score) { for (File file : File.values()) { List> sameFile = this.board.entrySet().stream() .filter(entry -> File.of(entry.getKey().getFile()).equals(file)) .filter(entry -> entry.getValue().isPawn() && !entry.getValue().isEnemy(team)) .collect(Collectors.toList()); + if (sameFile.size() > 1) { score -= sameFile.size() * 0.5; } diff --git a/src/main/java/chess/domain/move/PathFinder.java b/src/main/java/chess/domain/move/DirectionStrategyFactory.java similarity index 96% rename from src/main/java/chess/domain/move/PathFinder.java rename to src/main/java/chess/domain/move/DirectionStrategyFactory.java index 043af998b1e..ecd1202b79e 100644 --- a/src/main/java/chess/domain/move/PathFinder.java +++ b/src/main/java/chess/domain/move/DirectionStrategyFactory.java @@ -3,7 +3,7 @@ import chess.domain.move.direction.*; import chess.domain.position.Position; -public class PathFinder { +public class DirectionStrategyFactory { public static DirectionStrategy find(Position source, Position target) { int fileGap = target.calculateFileGap(source); int rankGap = target.calculateRankGap(source); diff --git a/src/main/java/chess/domain/move/MoveStrategy.java b/src/main/java/chess/domain/move/MoveStrategy.java index bb43e5055c3..f345d60fc2a 100644 --- a/src/main/java/chess/domain/move/MoveStrategy.java +++ b/src/main/java/chess/domain/move/MoveStrategy.java @@ -13,10 +13,8 @@ protected boolean isSamePosition(Position source, Position target) { return source.equals(target); } - public abstract boolean movable(Position source, Position target, Board board); - protected boolean checkObstacle(Position source, Position target, Board board) { - DirectionStrategy directionStrategy = PathFinder.find(source, target); + DirectionStrategy directionStrategy = DirectionStrategyFactory.find(source, target); List path = directionStrategy.find(source, target); for (Position position : path) { @@ -35,4 +33,6 @@ protected boolean checkTarget(Position source, Position target, Board board) { Piece targetPiece = board.getPiece(target); return sourcePiece.isEnemy(targetPiece); } + + public abstract boolean movable(Position source, Position target, Board board); } diff --git a/src/main/java/chess/domain/piece/Piece.java b/src/main/java/chess/domain/piece/Piece.java index 46befc3474c..72b62745474 100644 --- a/src/main/java/chess/domain/piece/Piece.java +++ b/src/main/java/chess/domain/piece/Piece.java @@ -13,19 +13,19 @@ public Piece(final PieceType pieceType, final Team team) { } public String toSymbol() { - return this.team.convert(this.pieceType.getSymbol()); + return this.team.symbolize(this.pieceType.getSymbol()); } - public boolean move(Position source, Position target, Board board) { - return this.pieceType.move(source, target, board); + public boolean movable(Position source, Position target, Board board) { + return this.pieceType.movable(source, target, board); } public boolean isEnemy(Piece targetPiece) { - return this.team.isEnemy(targetPiece.getTeam()); + return !this.team.isSameTeamWith(targetPiece.getTeam()); } public boolean isEnemy(Team team) { - return this.team.isEnemy(team); + return !this.team.isSameTeamWith(team); } public boolean isWhiteKing() { @@ -36,6 +36,10 @@ public boolean isBlackKing() { return this.pieceType.isKing() && !this.team.isWhite(); } + public boolean isPawn() { + return this.pieceType.isPawn(); + } + public Team getTeam() { return this.team; } @@ -43,8 +47,4 @@ public Team getTeam() { public double getScore() { return this.pieceType.getScore(); } - - public boolean isPawn() { - return this.pieceType.isPawn(); - } } diff --git a/src/main/java/chess/domain/piece/PieceType.java b/src/main/java/chess/domain/piece/PieceType.java index c9594930798..e503bf706f3 100644 --- a/src/main/java/chess/domain/piece/PieceType.java +++ b/src/main/java/chess/domain/piece/PieceType.java @@ -22,11 +22,7 @@ public enum PieceType { this.moveStrategy = moveStrategy; } - public String getSymbol() { - return symbol; - } - - public boolean move(Position source, Position target, Board board) { + public boolean movable(Position source, Position target, Board board) { return this.moveStrategy.movable(source, target, board); } @@ -34,11 +30,15 @@ public boolean isKing() { return this == KING; } + public boolean isPawn() { + return this == PAWN; + } + public double getScore() { return score; } - public boolean isPawn() { - return this == PAWN; + public String getSymbol() { + return symbol; } } \ No newline at end of file diff --git a/src/main/java/chess/domain/piece/Team.java b/src/main/java/chess/domain/piece/Team.java index bd6eae9ddb3..8b7d025abe0 100644 --- a/src/main/java/chess/domain/piece/Team.java +++ b/src/main/java/chess/domain/piece/Team.java @@ -12,19 +12,19 @@ public enum Team { this.expression = expression; } - public static Team changeTurn(Team team) { + public static Team changeTeam(Team team) { if (team == BLACK) { return WHITE; } return BLACK; } - public String convert(final String name) { + public String symbolize(final String name) { return this.expression.apply(name); } - public boolean isEnemy(Team team) { - return this != team; + public boolean isSameTeamWith(Team team) { + return this == team; } public boolean isWhite() { diff --git a/src/main/java/chess/domain/position/File.java b/src/main/java/chess/domain/position/File.java index 51666ff95e8..29f6ad3747a 100644 --- a/src/main/java/chess/domain/position/File.java +++ b/src/main/java/chess/domain/position/File.java @@ -37,8 +37,4 @@ public static File of(int file) { public int getNumber() { return number; } - - public int getSymbol() { - return this.symbol; - } } diff --git a/src/main/java/chess/domain/position/Rank.java b/src/main/java/chess/domain/position/Rank.java index 86f966f7544..f1034ef6464 100644 --- a/src/main/java/chess/domain/position/Rank.java +++ b/src/main/java/chess/domain/position/Rank.java @@ -29,14 +29,13 @@ public static Rank of(int rank) { return Arrays.stream(values()) .filter(f -> f.symbol == rank) .findFirst() - .orElseThrow(() -> new IllegalArgumentException("잘못된 x 좌표값을 입력하였습니다.")); + .orElseThrow(() -> new IllegalArgumentException("잘못된 y 좌표값을 입력하였습니다.")); } public int getSymbol() { return this.symbol; } - public int getDifference(Rank rank) { return this.symbol - rank.symbol; } diff --git a/src/main/java/chess/view/ConsoleInputView.java b/src/main/java/chess/view/ConsoleInputView.java index 83347cc5bd3..89b07e3f2a4 100644 --- a/src/main/java/chess/view/ConsoleInputView.java +++ b/src/main/java/chess/view/ConsoleInputView.java @@ -15,7 +15,7 @@ public boolean askChessRun() { System.out.println("> 게임 이동 : move source위치 target위치 - 예. move b2 b3"); try { String input = SCANNER.nextLine(); - validateCommand(input); + validateRunCommand(input); return runFlag(input); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); @@ -23,17 +23,14 @@ public boolean askChessRun() { } } - private void validateCommand(String input) { + private void validateRunCommand(String input) { if (!input.equals(START_COMMAND) && !input.equals(END_COMMAND)) { throw new IllegalArgumentException("start 또는 end 를 입력해주세요."); } } private boolean runFlag(String input) { - if (input.equals(START_COMMAND)) { - return true; - } - return false; + return input.equals(START_COMMAND); } @Override From 236e0661ce39abb6427cd97a80411db897fc9d44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=98=88=EB=B9=88?= Date: Fri, 27 Mar 2020 13:40:54 +0900 Subject: [PATCH 17/29] =?UTF-8?q?refactor:=20=EB=B0=A9=ED=96=A5=20?= =?UTF-8?q?=EC=A0=84=EB=9E=B5=20=EC=83=9D=EC=84=B1=20=EB=B6=84=EA=B8=B0?= =?UTF-8?q?=EB=AC=B8=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/chess/domain/ChessRunner.java | 2 +- .../chess/domain/board/BoardInitializer.java | 2 +- .../domain/move/DirectionStrategyFactory.java | 37 ------------------- .../java/chess/domain/piece/PieceType.java | 2 +- .../initialize/BishopInitializer.java | 2 +- .../initialize/InitializeStrategy.java | 2 +- .../initialize/KingInitializer.java | 2 +- .../initialize/KnightInitializer.java | 2 +- .../initialize/PawnInitializer.java | 2 +- .../initialize/QueenInitializer.java | 2 +- .../initialize/RookInitializer.java | 2 +- .../move/BishopMoveStrategy.java | 2 +- .../{ => strategy}/move/KingMoveStrategy.java | 2 +- .../move/KnightMoveStrategy.java | 2 +- .../{ => strategy}/move/MoveStrategy.java | 15 +++----- .../{ => strategy}/move/PawnMoveStrategy.java | 2 +- .../move/QueenMoveStrategy.java | 2 +- .../{ => strategy}/move/RookMoveStrategy.java | 2 +- .../strategy/move/direction/Direction.java | 36 ++++++++++++++++++ .../move/direction/DirectionStrategy.java | 2 +- .../move/direction/DownStrategy.java | 2 +- .../move/direction/LeftDownStrategy.java | 2 +- .../move/direction/LeftStrategy.java | 2 +- .../move/direction/LeftUpStrategy.java | 2 +- .../move/direction/RightDownStrategy.java | 2 +- .../move/direction/RightStrategy.java | 2 +- .../move/direction/RightUpStrategy.java | 2 +- .../move/direction/UpStrategy.java | 2 +- 28 files changed, 67 insertions(+), 71 deletions(-) delete mode 100644 src/main/java/chess/domain/move/DirectionStrategyFactory.java rename src/main/java/chess/domain/{ => strategy}/initialize/BishopInitializer.java (94%) rename src/main/java/chess/domain/{ => strategy}/initialize/InitializeStrategy.java (80%) rename src/main/java/chess/domain/{ => strategy}/initialize/KingInitializer.java (93%) rename src/main/java/chess/domain/{ => strategy}/initialize/KnightInitializer.java (94%) rename src/main/java/chess/domain/{ => strategy}/initialize/PawnInitializer.java (97%) rename src/main/java/chess/domain/{ => strategy}/initialize/QueenInitializer.java (93%) rename src/main/java/chess/domain/{ => strategy}/initialize/RookInitializer.java (94%) rename src/main/java/chess/domain/{ => strategy}/move/BishopMoveStrategy.java (94%) rename src/main/java/chess/domain/{ => strategy}/move/KingMoveStrategy.java (93%) rename src/main/java/chess/domain/{ => strategy}/move/KnightMoveStrategy.java (94%) rename src/main/java/chess/domain/{ => strategy}/move/MoveStrategy.java (71%) rename src/main/java/chess/domain/{ => strategy}/move/PawnMoveStrategy.java (97%) rename src/main/java/chess/domain/{ => strategy}/move/QueenMoveStrategy.java (91%) rename src/main/java/chess/domain/{ => strategy}/move/RookMoveStrategy.java (94%) create mode 100644 src/main/java/chess/domain/strategy/move/direction/Direction.java rename src/main/java/chess/domain/{ => strategy}/move/direction/DirectionStrategy.java (77%) rename src/main/java/chess/domain/{ => strategy}/move/direction/DownStrategy.java (90%) rename src/main/java/chess/domain/{ => strategy}/move/direction/LeftDownStrategy.java (91%) rename src/main/java/chess/domain/{ => strategy}/move/direction/LeftStrategy.java (90%) rename src/main/java/chess/domain/{ => strategy}/move/direction/LeftUpStrategy.java (91%) rename src/main/java/chess/domain/{ => strategy}/move/direction/RightDownStrategy.java (91%) rename src/main/java/chess/domain/{ => strategy}/move/direction/RightStrategy.java (90%) rename src/main/java/chess/domain/{ => strategy}/move/direction/RightUpStrategy.java (91%) rename src/main/java/chess/domain/{ => strategy}/move/direction/UpStrategy.java (90%) diff --git a/src/main/java/chess/domain/ChessRunner.java b/src/main/java/chess/domain/ChessRunner.java index 9adfae4119f..3a8845d409d 100644 --- a/src/main/java/chess/domain/ChessRunner.java +++ b/src/main/java/chess/domain/ChessRunner.java @@ -19,7 +19,7 @@ public void update(String source, String target) { Position targetPosition = Position.of(target); Piece selectedPiece = this.board.getPiece(sourcePosition); - if ((currentTeam.isSameTeamWith(selectedPiece.getTeam()))) { + if (!(currentTeam.isSameTeamWith(selectedPiece.getTeam()))) { throw new IllegalArgumentException("현재 차례가 아닙니다."); } diff --git a/src/main/java/chess/domain/board/BoardInitializer.java b/src/main/java/chess/domain/board/BoardInitializer.java index 614699b0424..e9a2a83ccb2 100644 --- a/src/main/java/chess/domain/board/BoardInitializer.java +++ b/src/main/java/chess/domain/board/BoardInitializer.java @@ -1,6 +1,6 @@ package chess.domain.board; -import chess.domain.initialize.*; +import chess.domain.strategy.initialize.*; import chess.domain.piece.Piece; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/move/DirectionStrategyFactory.java b/src/main/java/chess/domain/move/DirectionStrategyFactory.java deleted file mode 100644 index ecd1202b79e..00000000000 --- a/src/main/java/chess/domain/move/DirectionStrategyFactory.java +++ /dev/null @@ -1,37 +0,0 @@ -package chess.domain.move; - -import chess.domain.move.direction.*; -import chess.domain.position.Position; - -public class DirectionStrategyFactory { - public static DirectionStrategy find(Position source, Position target) { - int fileGap = target.calculateFileGap(source); - int rankGap = target.calculateRankGap(source); - - if (fileGap == 0 && rankGap > 0) { - return new UpStrategy(); - } - if (fileGap == 0 && rankGap < 0) { - return new DownStrategy(); - } - if (fileGap > 0 && rankGap == 0) { - return new RightStrategy(); - } - if (fileGap < 0 && rankGap == 0) { - return new LeftStrategy(); - } - if (fileGap > 0 && rankGap > 0) { - return new RightUpStrategy(); - } - if (fileGap > 0 && rankGap < 0) { - return new RightDownStrategy(); - } - if (fileGap < 0 && rankGap > 0) { - return new LeftUpStrategy(); - } - if (fileGap < 0 && rankGap < 0) { - return new LeftDownStrategy(); - } - throw new AssertionError(); - } -} diff --git a/src/main/java/chess/domain/piece/PieceType.java b/src/main/java/chess/domain/piece/PieceType.java index e503bf706f3..02df3964bd4 100644 --- a/src/main/java/chess/domain/piece/PieceType.java +++ b/src/main/java/chess/domain/piece/PieceType.java @@ -1,7 +1,7 @@ package chess.domain.piece; import chess.domain.board.Board; -import chess.domain.move.*; +import chess.domain.strategy.move.*; import chess.domain.position.Position; public enum PieceType { diff --git a/src/main/java/chess/domain/initialize/BishopInitializer.java b/src/main/java/chess/domain/strategy/initialize/BishopInitializer.java similarity index 94% rename from src/main/java/chess/domain/initialize/BishopInitializer.java rename to src/main/java/chess/domain/strategy/initialize/BishopInitializer.java index da628c0905d..aa96685bbe1 100644 --- a/src/main/java/chess/domain/initialize/BishopInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/BishopInitializer.java @@ -1,4 +1,4 @@ -package chess.domain.initialize; +package chess.domain.strategy.initialize; import chess.domain.piece.Piece; import chess.domain.piece.PieceType; diff --git a/src/main/java/chess/domain/initialize/InitializeStrategy.java b/src/main/java/chess/domain/strategy/initialize/InitializeStrategy.java similarity index 80% rename from src/main/java/chess/domain/initialize/InitializeStrategy.java rename to src/main/java/chess/domain/strategy/initialize/InitializeStrategy.java index 47fc1403522..18ae42a7b9d 100644 --- a/src/main/java/chess/domain/initialize/InitializeStrategy.java +++ b/src/main/java/chess/domain/strategy/initialize/InitializeStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.initialize; +package chess.domain.strategy.initialize; import chess.domain.piece.Piece; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/initialize/KingInitializer.java b/src/main/java/chess/domain/strategy/initialize/KingInitializer.java similarity index 93% rename from src/main/java/chess/domain/initialize/KingInitializer.java rename to src/main/java/chess/domain/strategy/initialize/KingInitializer.java index 9ce672ddc12..31346c488f2 100644 --- a/src/main/java/chess/domain/initialize/KingInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/KingInitializer.java @@ -1,4 +1,4 @@ -package chess.domain.initialize; +package chess.domain.strategy.initialize; import chess.domain.piece.Piece; import chess.domain.piece.PieceType; diff --git a/src/main/java/chess/domain/initialize/KnightInitializer.java b/src/main/java/chess/domain/strategy/initialize/KnightInitializer.java similarity index 94% rename from src/main/java/chess/domain/initialize/KnightInitializer.java rename to src/main/java/chess/domain/strategy/initialize/KnightInitializer.java index a8f3edfd4fb..610e7e8864c 100644 --- a/src/main/java/chess/domain/initialize/KnightInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/KnightInitializer.java @@ -1,4 +1,4 @@ -package chess.domain.initialize; +package chess.domain.strategy.initialize; import chess.domain.piece.Piece; import chess.domain.piece.PieceType; diff --git a/src/main/java/chess/domain/initialize/PawnInitializer.java b/src/main/java/chess/domain/strategy/initialize/PawnInitializer.java similarity index 97% rename from src/main/java/chess/domain/initialize/PawnInitializer.java rename to src/main/java/chess/domain/strategy/initialize/PawnInitializer.java index ced1279ba67..fae533df5d9 100644 --- a/src/main/java/chess/domain/initialize/PawnInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/PawnInitializer.java @@ -1,4 +1,4 @@ -package chess.domain.initialize; +package chess.domain.strategy.initialize; import chess.domain.piece.Piece; import chess.domain.piece.PieceType; diff --git a/src/main/java/chess/domain/initialize/QueenInitializer.java b/src/main/java/chess/domain/strategy/initialize/QueenInitializer.java similarity index 93% rename from src/main/java/chess/domain/initialize/QueenInitializer.java rename to src/main/java/chess/domain/strategy/initialize/QueenInitializer.java index 507f401250c..d13feded160 100644 --- a/src/main/java/chess/domain/initialize/QueenInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/QueenInitializer.java @@ -1,4 +1,4 @@ -package chess.domain.initialize; +package chess.domain.strategy.initialize; import chess.domain.piece.Piece; import chess.domain.piece.PieceType; diff --git a/src/main/java/chess/domain/initialize/RookInitializer.java b/src/main/java/chess/domain/strategy/initialize/RookInitializer.java similarity index 94% rename from src/main/java/chess/domain/initialize/RookInitializer.java rename to src/main/java/chess/domain/strategy/initialize/RookInitializer.java index 47fd77a442e..c1409b0f6c0 100644 --- a/src/main/java/chess/domain/initialize/RookInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/RookInitializer.java @@ -1,4 +1,4 @@ -package chess.domain.initialize; +package chess.domain.strategy.initialize; import chess.domain.piece.Piece; import chess.domain.piece.PieceType; diff --git a/src/main/java/chess/domain/move/BishopMoveStrategy.java b/src/main/java/chess/domain/strategy/move/BishopMoveStrategy.java similarity index 94% rename from src/main/java/chess/domain/move/BishopMoveStrategy.java rename to src/main/java/chess/domain/strategy/move/BishopMoveStrategy.java index 131b5e079da..60fc5310997 100644 --- a/src/main/java/chess/domain/move/BishopMoveStrategy.java +++ b/src/main/java/chess/domain/strategy/move/BishopMoveStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.move; +package chess.domain.strategy.move; import chess.domain.board.Board; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/move/KingMoveStrategy.java b/src/main/java/chess/domain/strategy/move/KingMoveStrategy.java similarity index 93% rename from src/main/java/chess/domain/move/KingMoveStrategy.java rename to src/main/java/chess/domain/strategy/move/KingMoveStrategy.java index c4e9a086426..86893b86e6b 100644 --- a/src/main/java/chess/domain/move/KingMoveStrategy.java +++ b/src/main/java/chess/domain/strategy/move/KingMoveStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.move; +package chess.domain.strategy.move; import chess.domain.board.Board; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/move/KnightMoveStrategy.java b/src/main/java/chess/domain/strategy/move/KnightMoveStrategy.java similarity index 94% rename from src/main/java/chess/domain/move/KnightMoveStrategy.java rename to src/main/java/chess/domain/strategy/move/KnightMoveStrategy.java index 484d2e3ae2d..6a7582c9bbb 100644 --- a/src/main/java/chess/domain/move/KnightMoveStrategy.java +++ b/src/main/java/chess/domain/strategy/move/KnightMoveStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.move; +package chess.domain.strategy.move; import chess.domain.board.Board; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/move/MoveStrategy.java b/src/main/java/chess/domain/strategy/move/MoveStrategy.java similarity index 71% rename from src/main/java/chess/domain/move/MoveStrategy.java rename to src/main/java/chess/domain/strategy/move/MoveStrategy.java index f345d60fc2a..d7beb3201b5 100644 --- a/src/main/java/chess/domain/move/MoveStrategy.java +++ b/src/main/java/chess/domain/strategy/move/MoveStrategy.java @@ -1,7 +1,8 @@ -package chess.domain.move; +package chess.domain.strategy.move; import chess.domain.board.Board; -import chess.domain.move.direction.DirectionStrategy; +import chess.domain.strategy.move.direction.Direction; +import chess.domain.strategy.move.direction.DirectionStrategy; import chess.domain.piece.Piece; import chess.domain.position.Position; @@ -14,15 +15,11 @@ protected boolean isSamePosition(Position source, Position target) { } protected boolean checkObstacle(Position source, Position target, Board board) { - DirectionStrategy directionStrategy = DirectionStrategyFactory.find(source, target); + DirectionStrategy directionStrategy = Direction.find(source, target); List path = directionStrategy.find(source, target); - for (Position position : path) { - if (!board.isEmpty(position)) { - return false; - } - } - return true; + return path.stream() + .anyMatch(position -> !board.isEmpty(position)); } protected boolean checkTarget(Position source, Position target, Board board) { diff --git a/src/main/java/chess/domain/move/PawnMoveStrategy.java b/src/main/java/chess/domain/strategy/move/PawnMoveStrategy.java similarity index 97% rename from src/main/java/chess/domain/move/PawnMoveStrategy.java rename to src/main/java/chess/domain/strategy/move/PawnMoveStrategy.java index 58981836295..ab116760b22 100644 --- a/src/main/java/chess/domain/move/PawnMoveStrategy.java +++ b/src/main/java/chess/domain/strategy/move/PawnMoveStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.move; +package chess.domain.strategy.move; import chess.domain.board.Board; import chess.domain.piece.Piece; diff --git a/src/main/java/chess/domain/move/QueenMoveStrategy.java b/src/main/java/chess/domain/strategy/move/QueenMoveStrategy.java similarity index 91% rename from src/main/java/chess/domain/move/QueenMoveStrategy.java rename to src/main/java/chess/domain/strategy/move/QueenMoveStrategy.java index 3cb9525322b..4a8f9dbbd6f 100644 --- a/src/main/java/chess/domain/move/QueenMoveStrategy.java +++ b/src/main/java/chess/domain/strategy/move/QueenMoveStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.move; +package chess.domain.strategy.move; import chess.domain.board.Board; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/move/RookMoveStrategy.java b/src/main/java/chess/domain/strategy/move/RookMoveStrategy.java similarity index 94% rename from src/main/java/chess/domain/move/RookMoveStrategy.java rename to src/main/java/chess/domain/strategy/move/RookMoveStrategy.java index 67ce216c581..6b46d56f9a0 100644 --- a/src/main/java/chess/domain/move/RookMoveStrategy.java +++ b/src/main/java/chess/domain/strategy/move/RookMoveStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.move; +package chess.domain.strategy.move; import chess.domain.board.Board; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/strategy/move/direction/Direction.java b/src/main/java/chess/domain/strategy/move/direction/Direction.java new file mode 100644 index 00000000000..0b16d539acf --- /dev/null +++ b/src/main/java/chess/domain/strategy/move/direction/Direction.java @@ -0,0 +1,36 @@ +package chess.domain.strategy.move.direction; + +import chess.domain.position.Position; + +import java.util.Arrays; +import java.util.function.BiPredicate; + +public enum Direction { + UP(new UpStrategy(), (fileGap, rankGap) -> fileGap == 0 && rankGap > 0), + DOWN(new DownStrategy(), (fileGap, rankGap) -> fileGap == 0 && rankGap < 0), + LEFT(new LeftStrategy(), (fileGap, rankGap) -> fileGap < 0 && rankGap == 0), + RIGHT(new RightStrategy(), (fileGap, rankGap) -> fileGap > 0 && rankGap == 0), + LEFT_UP(new LeftUpStrategy(), (fileGap, rankGap) -> fileGap < 0 && rankGap > 0), + LEFT_DOWN(new LeftDownStrategy(), (fileGap, rankGap) -> fileGap < 0 && rankGap < 0), + RIGHT_UP(new RightUpStrategy(), (fileGap, rankGap) -> fileGap > 0 && rankGap > 0), + RIGHT_DOWN(new RightDownStrategy(), (fileGap, rankGap) -> fileGap > 0 && rankGap < 0); + + private DirectionStrategy directionStrategy; + private BiPredicate condition; + + Direction(DirectionStrategy directionStrategy, BiPredicate condition) { + this.directionStrategy = directionStrategy; + this.condition = condition; + } + + public static DirectionStrategy find(Position source, Position target) { + int fileGap = target.calculateFileGap(source); + int rankGap = target.calculateRankGap(source); + + return Arrays.stream(values()) + .filter(direction -> direction.condition.test(fileGap, rankGap)) + .findFirst() + .map(direction -> direction.directionStrategy) + .orElseThrow(AssertionError::new); + } +} \ No newline at end of file diff --git a/src/main/java/chess/domain/move/direction/DirectionStrategy.java b/src/main/java/chess/domain/strategy/move/direction/DirectionStrategy.java similarity index 77% rename from src/main/java/chess/domain/move/direction/DirectionStrategy.java rename to src/main/java/chess/domain/strategy/move/direction/DirectionStrategy.java index 298b0eeed25..3b7594e165c 100644 --- a/src/main/java/chess/domain/move/direction/DirectionStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/DirectionStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.move.direction; +package chess.domain.strategy.move.direction; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/move/direction/DownStrategy.java b/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java similarity index 90% rename from src/main/java/chess/domain/move/direction/DownStrategy.java rename to src/main/java/chess/domain/strategy/move/direction/DownStrategy.java index 6ce3899e91a..ce41d8129e8 100644 --- a/src/main/java/chess/domain/move/direction/DownStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.move.direction; +package chess.domain.strategy.move.direction; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/move/direction/LeftDownStrategy.java b/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java similarity index 91% rename from src/main/java/chess/domain/move/direction/LeftDownStrategy.java rename to src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java index a2950d3d9b3..009cafb531b 100644 --- a/src/main/java/chess/domain/move/direction/LeftDownStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.move.direction; +package chess.domain.strategy.move.direction; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/move/direction/LeftStrategy.java b/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java similarity index 90% rename from src/main/java/chess/domain/move/direction/LeftStrategy.java rename to src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java index 8189c9a41b9..1e160c1d7e1 100644 --- a/src/main/java/chess/domain/move/direction/LeftStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.move.direction; +package chess.domain.strategy.move.direction; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/move/direction/LeftUpStrategy.java b/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java similarity index 91% rename from src/main/java/chess/domain/move/direction/LeftUpStrategy.java rename to src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java index f2a8719eaa3..78d922aac0a 100644 --- a/src/main/java/chess/domain/move/direction/LeftUpStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.move.direction; +package chess.domain.strategy.move.direction; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/move/direction/RightDownStrategy.java b/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java similarity index 91% rename from src/main/java/chess/domain/move/direction/RightDownStrategy.java rename to src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java index ce28c51645f..c34489a93db 100644 --- a/src/main/java/chess/domain/move/direction/RightDownStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.move.direction; +package chess.domain.strategy.move.direction; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/move/direction/RightStrategy.java b/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java similarity index 90% rename from src/main/java/chess/domain/move/direction/RightStrategy.java rename to src/main/java/chess/domain/strategy/move/direction/RightStrategy.java index f07bdf3360b..674c19beb5f 100644 --- a/src/main/java/chess/domain/move/direction/RightStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.move.direction; +package chess.domain.strategy.move.direction; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/move/direction/RightUpStrategy.java b/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java similarity index 91% rename from src/main/java/chess/domain/move/direction/RightUpStrategy.java rename to src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java index b19bd61bd58..27c9d5396d0 100644 --- a/src/main/java/chess/domain/move/direction/RightUpStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.move.direction; +package chess.domain.strategy.move.direction; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/move/direction/UpStrategy.java b/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java similarity index 90% rename from src/main/java/chess/domain/move/direction/UpStrategy.java rename to src/main/java/chess/domain/strategy/move/direction/UpStrategy.java index 1bcf3de6da6..ee128dbae6e 100644 --- a/src/main/java/chess/domain/move/direction/UpStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.move.direction; +package chess.domain.strategy.move.direction; import chess.domain.position.Position; From bf61f63031d9a644c9560a8480f3264a65797b19 Mon Sep 17 00:00:00 2001 From: giantim Date: Fri, 27 Mar 2020 14:30:57 +0900 Subject: [PATCH 18/29] =?UTF-8?q?refactor:=20=ED=85=8C=EC=8A=A4=ED=8A=B8?= =?UTF-8?q?=20=EC=BD=94=EB=93=9C=20=EB=94=94=EB=A0=89=ED=86=A0=EB=A6=AC=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 --- .../domain/strategy/move/BishopMoveStrategyTest.java | 12 ++++++++++++ .../strategy/move/direction/DirectionTest.java | 12 ++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 src/test/java/chess/domain/strategy/move/BishopMoveStrategyTest.java create mode 100644 src/test/java/chess/domain/strategy/move/direction/DirectionTest.java diff --git a/src/test/java/chess/domain/strategy/move/BishopMoveStrategyTest.java b/src/test/java/chess/domain/strategy/move/BishopMoveStrategyTest.java new file mode 100644 index 00000000000..2985b56b07d --- /dev/null +++ b/src/test/java/chess/domain/strategy/move/BishopMoveStrategyTest.java @@ -0,0 +1,12 @@ +package chess.domain.strategy.move; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class BishopMoveStrategyTest { + @DisplayName("비숍의 우 상단 대각 이동") + @Test + void rightUpTest() { + + } +} diff --git a/src/test/java/chess/domain/strategy/move/direction/DirectionTest.java b/src/test/java/chess/domain/strategy/move/direction/DirectionTest.java new file mode 100644 index 00000000000..778ade7f67a --- /dev/null +++ b/src/test/java/chess/domain/strategy/move/direction/DirectionTest.java @@ -0,0 +1,12 @@ +package chess.domain.strategy.move.direction; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class DirectionTest { + @DisplayName("조건에 맞는 방향 반환") + @Test + void findTest() { + + } +} From 9d29cfd67a4cd03155e70af099f24ce62b37b034 Mon Sep 17 00:00:00 2001 From: giantim Date: Fri, 27 Mar 2020 18:50:55 +0900 Subject: [PATCH 19/29] =?UTF-8?q?refactor:=20=ED=85=8C=EC=8A=A4=ED=8A=B8?= =?UTF-8?q?=20=EC=BD=94=EB=93=9C=20=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/domain/board/Board.java | 6 +- .../chess/domain/board/BoardInitializer.java | 2 +- .../java/chess/domain/piece/PieceType.java | 2 +- .../domain/strategy/move/MoveStrategy.java | 9 +- .../strategy/move/direction/Direction.java | 9 +- .../move/direction/DirectionStrategy.java | 2 +- .../strategy/move/direction/DownStrategy.java | 2 +- .../move/direction/LeftDownStrategy.java | 6 +- .../strategy/move/direction/LeftStrategy.java | 2 +- .../move/direction/LeftUpStrategy.java | 2 +- .../move/direction/RightDownStrategy.java | 4 +- .../move/direction/RightStrategy.java | 2 +- .../move/direction/RightUpStrategy.java | 2 +- .../strategy/move/direction/UpStrategy.java | 2 +- .../java/chess/domain/ChessRunnerTest.java | 32 +++++ .../java/chess/domain/board/BoardTest.java | 107 +++++++++++++++++ .../java/chess/domain/piece/PieceTest.java | 52 ++++++++ .../java/chess/domain/piece/TeamTest.java | 17 +++ .../strategy/move/BishopMoveStrategyTest.java | 65 ++++++++++ .../strategy/move/KingMoveStrategyTest.java | 64 ++++++++++ .../strategy/move/KnightMoveStrategyTest.java | 64 ++++++++++ .../strategy/move/PawnMoveStrategyTest.java | 107 +++++++++++++++++ .../strategy/move/QueenMoveStrategyTest.java | 113 ++++++++++++++++++ .../strategy/move/RookMoveStrategyTest.java | 77 ++++++++++++ .../move/direction/DirectionTest.java | 67 ++++++++++- 25 files changed, 793 insertions(+), 24 deletions(-) create mode 100644 src/test/java/chess/domain/ChessRunnerTest.java create mode 100644 src/test/java/chess/domain/board/BoardTest.java create mode 100644 src/test/java/chess/domain/piece/PieceTest.java create mode 100644 src/test/java/chess/domain/piece/TeamTest.java create mode 100644 src/test/java/chess/domain/strategy/move/KingMoveStrategyTest.java create mode 100644 src/test/java/chess/domain/strategy/move/KnightMoveStrategyTest.java create mode 100644 src/test/java/chess/domain/strategy/move/PawnMoveStrategyTest.java create mode 100644 src/test/java/chess/domain/strategy/move/QueenMoveStrategyTest.java create mode 100644 src/test/java/chess/domain/strategy/move/RookMoveStrategyTest.java diff --git a/src/main/java/chess/domain/board/Board.java b/src/main/java/chess/domain/board/Board.java index 0c5c21b5034..c685bab6c97 100644 --- a/src/main/java/chess/domain/board/Board.java +++ b/src/main/java/chess/domain/board/Board.java @@ -15,7 +15,11 @@ public class Board { private final Map board; public Board() { - this.board = BoardInitializer.initializeAll(); + this(BoardInitializer.initializeAll()); + } + + public Board(Map board) { + this.board = board; } public Map parse() { diff --git a/src/main/java/chess/domain/board/BoardInitializer.java b/src/main/java/chess/domain/board/BoardInitializer.java index e9a2a83ccb2..057eb7137b0 100644 --- a/src/main/java/chess/domain/board/BoardInitializer.java +++ b/src/main/java/chess/domain/board/BoardInitializer.java @@ -1,8 +1,8 @@ package chess.domain.board; -import chess.domain.strategy.initialize.*; import chess.domain.piece.Piece; import chess.domain.position.Position; +import chess.domain.strategy.initialize.*; import java.util.*; diff --git a/src/main/java/chess/domain/piece/PieceType.java b/src/main/java/chess/domain/piece/PieceType.java index 02df3964bd4..f14a48d6022 100644 --- a/src/main/java/chess/domain/piece/PieceType.java +++ b/src/main/java/chess/domain/piece/PieceType.java @@ -1,8 +1,8 @@ package chess.domain.piece; import chess.domain.board.Board; -import chess.domain.strategy.move.*; import chess.domain.position.Position; +import chess.domain.strategy.move.*; public enum PieceType { KING("k", 0, new KingMoveStrategy()), diff --git a/src/main/java/chess/domain/strategy/move/MoveStrategy.java b/src/main/java/chess/domain/strategy/move/MoveStrategy.java index d7beb3201b5..27ea9af6e81 100644 --- a/src/main/java/chess/domain/strategy/move/MoveStrategy.java +++ b/src/main/java/chess/domain/strategy/move/MoveStrategy.java @@ -1,10 +1,9 @@ package chess.domain.strategy.move; import chess.domain.board.Board; -import chess.domain.strategy.move.direction.Direction; -import chess.domain.strategy.move.direction.DirectionStrategy; import chess.domain.piece.Piece; import chess.domain.position.Position; +import chess.domain.strategy.move.direction.Direction; import java.util.List; @@ -15,11 +14,11 @@ protected boolean isSamePosition(Position source, Position target) { } protected boolean checkObstacle(Position source, Position target, Board board) { - DirectionStrategy directionStrategy = Direction.find(source, target); - List path = directionStrategy.find(source, target); + Direction direction = Direction.findDirection(source, target); + List path = direction.findPath(source, target); return path.stream() - .anyMatch(position -> !board.isEmpty(position)); + .allMatch(board::isEmpty); } protected boolean checkTarget(Position source, Position target, Board board) { diff --git a/src/main/java/chess/domain/strategy/move/direction/Direction.java b/src/main/java/chess/domain/strategy/move/direction/Direction.java index 0b16d539acf..48301427d30 100644 --- a/src/main/java/chess/domain/strategy/move/direction/Direction.java +++ b/src/main/java/chess/domain/strategy/move/direction/Direction.java @@ -3,6 +3,7 @@ import chess.domain.position.Position; import java.util.Arrays; +import java.util.List; import java.util.function.BiPredicate; public enum Direction { @@ -23,14 +24,16 @@ public enum Direction { this.condition = condition; } - public static DirectionStrategy find(Position source, Position target) { + public static Direction findDirection(Position source, Position target) { int fileGap = target.calculateFileGap(source); int rankGap = target.calculateRankGap(source); - return Arrays.stream(values()) .filter(direction -> direction.condition.test(fileGap, rankGap)) .findFirst() - .map(direction -> direction.directionStrategy) .orElseThrow(AssertionError::new); } + + public List findPath(Position source, Position target) { + return this.directionStrategy.findPath(source, target); + } } \ No newline at end of file diff --git a/src/main/java/chess/domain/strategy/move/direction/DirectionStrategy.java b/src/main/java/chess/domain/strategy/move/direction/DirectionStrategy.java index 3b7594e165c..d9d3f558288 100644 --- a/src/main/java/chess/domain/strategy/move/direction/DirectionStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/DirectionStrategy.java @@ -5,5 +5,5 @@ import java.util.List; public interface DirectionStrategy { - List find(Position source, Position target); + List findPath(Position source, Position target); } \ No newline at end of file diff --git a/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java b/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java index ce41d8129e8..d7d62a77070 100644 --- a/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java @@ -7,7 +7,7 @@ public class DownStrategy implements DirectionStrategy { @Override - public List find(Position source, Position target) { + public List findPath(Position source, Position target) { List path = new ArrayList<>(); for (int i = target.getRank() + 1; i < source.getRank(); i++) { diff --git a/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java b/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java index 009cafb531b..f6aecaba9d9 100644 --- a/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java @@ -8,13 +8,17 @@ public class LeftDownStrategy implements DirectionStrategy { @Override - public List find(Position source, Position target) { + public List findPath(Position source, Position target) { List path = new ArrayList<>(); for (int i = target.getFile() + 1; i < source.getFile(); i++) { path.add(Position.of(i, target.getRank() - (target.getFile() - i))); } +// List path2 = IntStream.range(target.getFile() + 1, source.getFile()) +// .mapToObj(index -> Position.of(index, target.getRank() - (target.getFile() - index))) +// .collect(Collectors.toList()); + return path; } } diff --git a/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java b/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java index 1e160c1d7e1..53fed6f5394 100644 --- a/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java @@ -7,7 +7,7 @@ public class LeftStrategy implements DirectionStrategy { @Override - public List find(Position source, Position target) { + public List findPath(Position source, Position target) { List path = new ArrayList<>(); for (int i = target.getFile() + 1; i < source.getFile(); i++) { diff --git a/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java b/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java index 78d922aac0a..20842f29f74 100644 --- a/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java @@ -7,7 +7,7 @@ public class LeftUpStrategy implements DirectionStrategy { @Override - public List find(Position source, Position target) { + public List findPath(Position source, Position target) { List path = new ArrayList<>(); for (int i = target.getFile() + 1; i < source.getFile(); i++) { diff --git a/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java b/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java index c34489a93db..d5919f032e8 100644 --- a/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java @@ -8,11 +8,11 @@ public class RightDownStrategy implements DirectionStrategy { @Override - public List find(Position source, Position target) { + public List findPath(Position source, Position target) { List path = new ArrayList<>(); for (int i = target.getFile() - 1; i > source.getFile(); i--) { - path.add(Position.of(i, target.getRank() - (target.getFile() - i))); + path.add(Position.of(i, target.getRank() + (target.getFile() - i))); } return path; diff --git a/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java b/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java index 674c19beb5f..2ce164b797c 100644 --- a/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java @@ -7,7 +7,7 @@ public class RightStrategy implements DirectionStrategy { @Override - public List find(Position source, Position target) { + public List findPath(Position source, Position target) { List path = new ArrayList<>(); for (int i = target.getFile() - 1; i > source.getFile(); i--) { diff --git a/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java b/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java index 27c9d5396d0..ce7a9472f12 100644 --- a/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java @@ -8,7 +8,7 @@ public class RightUpStrategy implements DirectionStrategy { @Override - public List find(Position source, Position target) { + public List findPath(Position source, Position target) { List path = new ArrayList<>(); for (int i = target.getFile() - 1; i > source.getFile(); i--) { diff --git a/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java b/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java index ee128dbae6e..9728fdc2e8f 100644 --- a/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java @@ -7,7 +7,7 @@ public class UpStrategy implements DirectionStrategy { @Override - public List find(Position source, Position target) { + public List findPath(Position source, Position target) { List path = new ArrayList<>(); for (int i = target.getRank() - 1; i > source.getRank(); i--) { diff --git a/src/test/java/chess/domain/ChessRunnerTest.java b/src/test/java/chess/domain/ChessRunnerTest.java new file mode 100644 index 00000000000..093fd56c2b9 --- /dev/null +++ b/src/test/java/chess/domain/ChessRunnerTest.java @@ -0,0 +1,32 @@ +package chess.domain; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class ChessRunnerTest { + ChessRunner chessRunner; + + @BeforeEach + void setUp() { + chessRunner = new ChessRunner(); + } + + @DisplayName("현재 순서가 아닐 때 에러 메시지 출력") + @Test + void validateCurrentTeam() { + assertThatThrownBy(() -> chessRunner.update("a7", "a5")) //블랙 팀 폰 이동 + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("현재 차례가 아닙니다."); + } + + @DisplayName("이동할 수 없는 곳일 때 에러 메시지 출력") + @Test + void validateMovable() { + assertThatThrownBy(() -> chessRunner.update("a1", "a2")) //화이트 팀 룩 이동 + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("이동할 수 없는 곳입니다."); + } +} \ No newline at end of file diff --git a/src/test/java/chess/domain/board/BoardTest.java b/src/test/java/chess/domain/board/BoardTest.java new file mode 100644 index 00000000000..9a0e11c066b --- /dev/null +++ b/src/test/java/chess/domain/board/BoardTest.java @@ -0,0 +1,107 @@ +package chess.domain.board; + +import chess.domain.piece.Piece; +import chess.domain.piece.PieceType; +import chess.domain.piece.Team; +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +public class BoardTest { + @DisplayName("빈 칸으로 말 이동") + @Test + void updateAtEmptyBoard() { + Board board = new Board(); + Position source = Position.of("a2"); + Position target = Position.of("a3"); + board.updateBoard(source, target); + + Assertions.assertThat(board.getPiece(source)).isNull(); + Assertions.assertThat(board.getPiece(target)).isNotNull(); + Assertions.assertThat(board.getPiece(target)).isInstanceOf(Piece.class); + } + + @DisplayName("상대 편으로 말 이동") + @Test + void updateAtEnemy() { + Piece rook = new Piece(PieceType.ROOK, Team.WHITE); + Piece pawn = new Piece(PieceType.PAWN, Team.BLACK); + Map entry = new HashMap<>(); + Position source = Position.of("a2"); + Position target = Position.of("a3"); + entry.put(source, rook); + entry.put(target, pawn); + Board board = new Board(entry); + board.updateBoard(source, target); + + Assertions.assertThat(board.getPiece(source)).isNull(); + Assertions.assertThat(board.getPiece(target)).isNotNull(); + Assertions.assertThat(board.getPiece(target)).isInstanceOf(Piece.class); + } + + @DisplayName("승자 팀을 판단") + @Test + void checkWinnerTest() { + Map whiteKing = new HashMap<>(); + whiteKing.put(Position.of("a3"), new Piece(PieceType.KING, Team.WHITE)); + Board whiteWinBoard = new Board(whiteKing); + + Map blackKing = new HashMap<>(); + blackKing.put(Position.of("b4"), new Piece(PieceType.KING, Team.BLACK)); + Board blackWinBoard = new Board(blackKing); + + Map bothKing = new HashMap<>(); + bothKing.put(Position.of("a5"), new Piece(PieceType.KING, Team.BLACK)); + bothKing.put(Position.of("b7"), new Piece(PieceType.KING, Team.WHITE)); + Board drawBoard = new Board(bothKing); + + Assertions.assertThat(whiteWinBoard.checkWinner()).isEqualTo(Team.WHITE); + Assertions.assertThat(blackWinBoard.checkWinner()).isEqualTo(Team.BLACK); + Assertions.assertThat(drawBoard.checkWinner()).isNull(); + } + + @DisplayName("지정한 칸이 비어있는지 판단") + @Test + void isEmptyTest() { + Position nonEmptyTarget = Position.of("a2"); + Position emptyTarget = Position.of("a3"); + Board board = new Board(); + + Assertions.assertThat(board.isEmpty(nonEmptyTarget)).isFalse(); + Assertions.assertThat(board.isEmpty(emptyTarget)).isTrue(); + } + + @DisplayName("지정한 칸의 체스 말 반환") + @Test + void getPieceTest() { + Board board = new Board(); + + Assertions.assertThat(board.getPiece(Position.of("a2"))).isInstanceOf(Piece.class); + Assertions.assertThat(board.getPiece(Position.of("a3"))).isNull(); + } + + @DisplayName("같은 세로줄에 폰이 없을 때 점수 계산") + @Test + void calculateScoreWithoutSameFilePawnTest() { + Board board = new Board(); + + Assertions.assertThat(board.calculateScore(Team.WHITE)).isEqualTo(38d); + Assertions.assertThat(board.calculateScore(Team.BLACK)).isEqualTo(38d); + } + + @DisplayName("같은 세로줄에 폰이 있을 때 점수 계산") + @Test + void calculateScoreWithSameFilePawn() { + Map sameFilePawn = new HashMap<>(); + sameFilePawn.put(Position.of("a3"), new Piece(PieceType.PAWN, Team.WHITE)); + sameFilePawn.put(Position.of("a4"), new Piece(PieceType.PAWN, Team.WHITE)); + sameFilePawn.put(Position.of("a5"), new Piece(PieceType.PAWN, Team.WHITE)); + Board board = new Board(sameFilePawn); + + Assertions.assertThat(board.calculateScore(Team.WHITE)).isEqualTo(1.5d); + } +} diff --git a/src/test/java/chess/domain/piece/PieceTest.java b/src/test/java/chess/domain/piece/PieceTest.java new file mode 100644 index 00000000000..088f7bc1eab --- /dev/null +++ b/src/test/java/chess/domain/piece/PieceTest.java @@ -0,0 +1,52 @@ +package chess.domain.piece; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class PieceTest { + @DisplayName("팀 별 대소문자로 출력") + @Test + void toSymbol() { + Piece whitePiece = new Piece(PieceType.BISHOP, Team.WHITE); + Piece blackPiece = new Piece(PieceType.BISHOP, Team.BLACK); + assertThat(whitePiece.toSymbol()).isEqualTo("b"); + assertThat(blackPiece.toSymbol()).isEqualTo("B"); + } + + @DisplayName("피스의 팀 구분") + @Test + void isEnemy() { + Piece whitePiece = new Piece(PieceType.KNIGHT, Team.WHITE); + Piece blackPiece = new Piece(PieceType.KNIGHT, Team.BLACK); + assertThat(whitePiece.isEnemy(blackPiece)).isTrue(); + } + + @DisplayName("피스가 흰 팀의 킹인지 테스트") + @Test + void isWhiteKing() { + Piece whiteKing = new Piece(PieceType.KING, Team.WHITE); + Piece blackBishop = new Piece(PieceType.BISHOP, Team.BLACK); + assertThat(whiteKing.isWhiteKing()).isTrue(); + assertThat(blackBishop.isWhiteKing()).isFalse(); + } + + @DisplayName("피스가 검은 팀의 킹인지 테스트") + @Test + void isBlackKing() { + Piece blackKing = new Piece(PieceType.KING, Team.BLACK); + Piece whiteBishop = new Piece(PieceType.BISHOP, Team.WHITE); + assertThat(blackKing.isBlackKing()).isTrue(); + assertThat(whiteBishop.isBlackKing()).isFalse(); + } + + @DisplayName("피스가 폰인지 테스트") + @Test + void isPawn() { + Piece whitePawn = new Piece(PieceType.PAWN, Team.WHITE); + Piece blackQueen = new Piece(PieceType.QUEEN, Team.BLACK); + assertThat(whitePawn.isPawn()).isTrue(); + assertThat(blackQueen.isPawn()).isFalse(); + } +} \ No newline at end of file diff --git a/src/test/java/chess/domain/piece/TeamTest.java b/src/test/java/chess/domain/piece/TeamTest.java new file mode 100644 index 00000000000..6578588c4a4 --- /dev/null +++ b/src/test/java/chess/domain/piece/TeamTest.java @@ -0,0 +1,17 @@ +package chess.domain.piece; + +import chess.domain.ChessRunner; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class TeamTest { + @DisplayName("팀 순서 변경 테스트") + @Test + void changeTeam() { + ChessRunner chessRunner = new ChessRunner(); + Team nextTeam = Team.changeTeam(chessRunner.getCurrentTeam()); + assertThat(nextTeam.isSameTeamWith(Team.BLACK)).isTrue(); + } +} \ No newline at end of file diff --git a/src/test/java/chess/domain/strategy/move/BishopMoveStrategyTest.java b/src/test/java/chess/domain/strategy/move/BishopMoveStrategyTest.java index 2985b56b07d..6bdeb3df2ca 100644 --- a/src/test/java/chess/domain/strategy/move/BishopMoveStrategyTest.java +++ b/src/test/java/chess/domain/strategy/move/BishopMoveStrategyTest.java @@ -1,12 +1,77 @@ package chess.domain.strategy.move; +import chess.domain.board.Board; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceType; +import chess.domain.piece.Team; +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import java.util.HashMap; +import java.util.Map; + public class BishopMoveStrategyTest { + private MoveStrategy bishopStrategy; + private Board board; + + @BeforeEach + private void setUp() { + bishopStrategy = new BishopMoveStrategy(); + Map emptyBoard = new HashMap<>(); + board = new Board(emptyBoard); + } + @DisplayName("비숍의 우 상단 대각 이동") @Test void rightUpTest() { + Position source = Position.of("a1"); + Position target = Position.of("e5"); + + Assertions.assertThat(bishopStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("비숍의 우 하단 대각 이동") + @Test + void rightDownTest() { + Position source = Position.of("a7"); + Position target = Position.of("e3"); + + Assertions.assertThat(bishopStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("비숍의 좌 상단 대각 이동") + @Test + void leftUpTest() { + Position source = Position.of("g1"); + Position target = Position.of("c5"); + + Assertions.assertThat(bishopStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("비숍의 좌 하단 대각 이동") + @Test + void leftDownTest() { + Position source = Position.of("g7"); + Position target = Position.of("c3"); + + Assertions.assertThat(bishopStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("타겟 위치에 적이 있을 때 이동") + @Test + void moveWhenEnemyTest() { + Piece bishop = new Piece(PieceType.BISHOP, Team.BLACK); + Piece enemy = new Piece(PieceType.PAWN, Team.WHITE); + Position source = Position.of("a1"); + Position target = Position.of("e5"); + Map enemyEntry = new HashMap<>(); + enemyEntry.put(source, bishop); + enemyEntry.put(target, enemy); + Board enemyBoard = new Board(enemyEntry); + Assertions.assertThat(bishopStrategy.movable(source, target, enemyBoard)).isTrue(); } } diff --git a/src/test/java/chess/domain/strategy/move/KingMoveStrategyTest.java b/src/test/java/chess/domain/strategy/move/KingMoveStrategyTest.java new file mode 100644 index 00000000000..0f54b0d7e69 --- /dev/null +++ b/src/test/java/chess/domain/strategy/move/KingMoveStrategyTest.java @@ -0,0 +1,64 @@ +package chess.domain.strategy.move; + +import chess.domain.board.Board; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceType; +import chess.domain.piece.Team; +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +public class KingMoveStrategyTest { + private MoveStrategy kingStrategy; + + @BeforeEach + private void setUp() { + kingStrategy = new KingMoveStrategy(); + } + + @DisplayName("킹의 이동 가능 위치에 대해 이동 테스트") + @Test + void moveTest() { + Map emptyBoard = new HashMap<>(); + Board board = new Board(emptyBoard); + Position source = Position.of("d4"); + + Position up = Position.of("d5"); + Position down = Position.of("d3"); + Position left = Position.of("c4"); + Position right = Position.of("e4"); + Position rightUp = Position.of("e5"); + Position rightDown = Position.of("e3"); + Position leftUp = Position.of("c5"); + Position leftDown = Position.of("c3"); + + Assertions.assertThat(kingStrategy.movable(source, up, board)).isTrue(); + Assertions.assertThat(kingStrategy.movable(source, down, board)).isTrue(); + Assertions.assertThat(kingStrategy.movable(source, left, board)).isTrue(); + Assertions.assertThat(kingStrategy.movable(source, right, board)).isTrue(); + Assertions.assertThat(kingStrategy.movable(source, rightUp, board)).isTrue(); + Assertions.assertThat(kingStrategy.movable(source, rightDown, board)).isTrue(); + Assertions.assertThat(kingStrategy.movable(source, leftUp, board)).isTrue(); + Assertions.assertThat(kingStrategy.movable(source, leftDown, board)).isTrue(); + } + + @DisplayName("타겟 위치에 적이 있을 때 이동") + @Test + void moveWhenEnemyTest() { + Piece king = new Piece(PieceType.KING, Team.BLACK); + Piece enemy = new Piece(PieceType.PAWN, Team.WHITE); + Position source = Position.of("d4"); + Position target = Position.of("e5"); + Map enemyEntry = new HashMap<>(); + enemyEntry.put(source, king); + enemyEntry.put(target, enemy); + Board enemyBoard = new Board(enemyEntry); + + Assertions.assertThat(kingStrategy.movable(source, target, enemyBoard)).isTrue(); + } +} diff --git a/src/test/java/chess/domain/strategy/move/KnightMoveStrategyTest.java b/src/test/java/chess/domain/strategy/move/KnightMoveStrategyTest.java new file mode 100644 index 00000000000..84bcf4d3aa8 --- /dev/null +++ b/src/test/java/chess/domain/strategy/move/KnightMoveStrategyTest.java @@ -0,0 +1,64 @@ +package chess.domain.strategy.move; + +import chess.domain.board.Board; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceType; +import chess.domain.piece.Team; +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +public class KnightMoveStrategyTest { + private MoveStrategy knightStrategy; + + @BeforeEach + private void setUp() { + knightStrategy = new KnightMoveStrategy(); + } + + @DisplayName("나이트의 이동 가능 위치에 이동") + @Test + void moveTest() { + Position source = Position.of("d4"); + Map emptyBoard = new HashMap<>(); + Board board = new Board(emptyBoard); + + Position upLeft = Position.of("c6"); + Position upRight = Position.of("e6"); + Position downLeft = Position.of("c2"); + Position downRight = Position.of("e2"); + Position leftUp = Position.of("b5"); + Position leftDown = Position.of("b3"); + Position rightUp = Position.of("f5"); + Position rightDown = Position.of("f3"); + + Assertions.assertThat(knightStrategy.movable(source, upLeft, board)).isTrue(); + Assertions.assertThat(knightStrategy.movable(source, upRight, board)).isTrue(); + Assertions.assertThat(knightStrategy.movable(source, downLeft, board)).isTrue(); + Assertions.assertThat(knightStrategy.movable(source, downRight, board)).isTrue(); + Assertions.assertThat(knightStrategy.movable(source, leftUp, board)).isTrue(); + Assertions.assertThat(knightStrategy.movable(source, leftDown, board)).isTrue(); + Assertions.assertThat(knightStrategy.movable(source, rightUp, board)).isTrue(); + Assertions.assertThat(knightStrategy.movable(source, rightDown, board)).isTrue(); + } + + @DisplayName("타겟 위치에 적이 있을 때 이동") + @Test + void moveWhenEnemyTest() { + Piece knight = new Piece(PieceType.KING, Team.BLACK); + Piece enemy = new Piece(PieceType.PAWN, Team.WHITE); + Position source = Position.of("d4"); + Position target = Position.of("e6"); + Map enemyEntry = new HashMap<>(); + enemyEntry.put(source, knight); + enemyEntry.put(target, enemy); + Board enemyBoard = new Board(enemyEntry); + + Assertions.assertThat(knightStrategy.movable(source, target, enemyBoard)).isTrue(); + } +} diff --git a/src/test/java/chess/domain/strategy/move/PawnMoveStrategyTest.java b/src/test/java/chess/domain/strategy/move/PawnMoveStrategyTest.java new file mode 100644 index 00000000000..41e2d60050c --- /dev/null +++ b/src/test/java/chess/domain/strategy/move/PawnMoveStrategyTest.java @@ -0,0 +1,107 @@ +package chess.domain.strategy.move; + +import chess.domain.board.Board; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceType; +import chess.domain.piece.Team; +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +public class PawnMoveStrategyTest { + private MoveStrategy pawnStrategy; + + @BeforeEach + private void setUp() { + pawnStrategy = new PawnMoveStrategy(); +// Piece whitePawn = new Piece(PieceType.PAWN, Team.WHITE); +// Piece blackPawn = new Piece(PieceType.PAWN, Team.BLACK); +// Position whiteSource = Position.of("d4"); +// Position blackSource = Position.of("d3"); +// Map entry = new HashMap<>(); +// entry.put(whiteSource, whitePawn); +// entry.put(blackSource, blackPawn); +// board = new Board(entry); + } + + @DisplayName("폰이 시작 위치일 때 1칸 또는 2칸 이동") + @Test + void moveAtInitialPosition() { + Piece whitePawn = new Piece(PieceType.PAWN, Team.WHITE); + Piece blackPawn = new Piece(PieceType.PAWN, Team.BLACK); + Position whiteInitial = Position.of("a2"); + Position blackInitial = Position.of("a7"); + Map emptyBoard = new HashMap<>(); + emptyBoard.put(whiteInitial, whitePawn); + emptyBoard.put(blackInitial, blackPawn); + Board board = new Board(emptyBoard); + + Position whiteOne = Position.of("a3"); + Position whiteTwo = Position.of("a4"); + Position blackOne = Position.of("a6"); + Position blackTwo = Position.of("a5"); + + Assertions.assertThat(pawnStrategy.movable(whiteInitial, whiteOne, board)).isTrue(); + Assertions.assertThat(pawnStrategy.movable(whiteInitial, whiteTwo, board)).isTrue(); + Assertions.assertThat(pawnStrategy.movable(blackInitial, blackOne, board)).isTrue(); + Assertions.assertThat(pawnStrategy.movable(blackInitial, blackTwo, board)).isTrue(); + } + + @DisplayName("폰이 시작 위치가 아닐 때 1칸 전진") + @Test + void moveAtNoneInitialPosition() { + Piece whitePawn = new Piece(PieceType.PAWN, Team.WHITE); + Piece blackPawn = new Piece(PieceType.PAWN, Team.BLACK); + Position whiteSource = Position.of("a3"); + Position blackSource = Position.of("a6"); + Map emptyBoard = new HashMap<>(); + emptyBoard.put(whiteSource, whitePawn); + emptyBoard.put(blackSource, blackPawn); + Board board = new Board(emptyBoard); + + Position upTarget = Position.of("a4"); + Position downTarget = Position.of("a5"); + + Assertions.assertThat(pawnStrategy.movable(whiteSource, upTarget, board)).isTrue(); + Assertions.assertThat(pawnStrategy.movable(blackSource, downTarget, board)).isTrue(); + } + + @DisplayName("폰이 시작 위치가 아닐 때 대각선의 적을 공격 가능") + @Test + void moveDiagonalTest() { + Piece whitePawn = new Piece(PieceType.PAWN, Team.WHITE); + Piece whiteLeftEnemy = new Piece(PieceType.PAWN, Team.BLACK); + Piece whiteRightEnemy = new Piece(PieceType.PAWN, Team.BLACK); + + Piece blackPawn = new Piece(PieceType.PAWN, Team.BLACK); + Piece blackLeftEnemy = new Piece(PieceType.PAWN, Team.WHITE); + Piece blackRightEnemy = new Piece(PieceType.PAWN, Team.WHITE); + + Position whiteSource = Position.of("d3"); + Position whiteDiagonalLeft = Position.of("c4"); + Position whiteDiagonalRight = Position.of("e4"); + + Position blackSource = Position.of("d6"); + Position blackDiagonalLeft = Position.of("c5"); + Position blackDiagonalRight = Position.of("e5"); + + Map entry = new HashMap<>(); + entry.put(whiteSource, whitePawn); + entry.put(whiteDiagonalLeft, whiteLeftEnemy); + entry.put(whiteDiagonalRight, whiteRightEnemy); + entry.put(blackSource, blackPawn); + entry.put(blackDiagonalLeft, blackLeftEnemy); + entry.put(blackDiagonalRight, blackRightEnemy); + Board board = new Board(entry); + + Assertions.assertThat(pawnStrategy.movable(whiteSource, whiteDiagonalLeft, board)).isTrue(); + Assertions.assertThat(pawnStrategy.movable(whiteSource, whiteDiagonalRight, board)).isTrue(); + Assertions.assertThat(pawnStrategy.movable(blackSource, blackDiagonalLeft, board)).isTrue(); + Assertions.assertThat(pawnStrategy.movable(blackSource, blackDiagonalRight, board)).isTrue(); + } +} diff --git a/src/test/java/chess/domain/strategy/move/QueenMoveStrategyTest.java b/src/test/java/chess/domain/strategy/move/QueenMoveStrategyTest.java new file mode 100644 index 00000000000..e1cc32da9fd --- /dev/null +++ b/src/test/java/chess/domain/strategy/move/QueenMoveStrategyTest.java @@ -0,0 +1,113 @@ +package chess.domain.strategy.move; + +import chess.domain.board.Board; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceType; +import chess.domain.piece.Team; +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +public class QueenMoveStrategyTest { + private MoveStrategy queenStrategy; + private Board board; + + @BeforeEach + private void setUp() { + queenStrategy = new QueenMoveStrategy(); + Map emptyBoard = new HashMap<>(); + board = new Board(emptyBoard); + } + + @DisplayName("퀸의 우 상단 대각 이동") + @Test + void rightUpTest() { + Position source = Position.of("a1"); + Position target = Position.of("e5"); + + Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("퀸의 우 하단 대각 이동") + @Test + void rightDownTest() { + Position source = Position.of("a7"); + Position target = Position.of("e3"); + + Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("퀸의 좌 상단 대각 이동") + @Test + void leftUpTest() { + Position source = Position.of("g1"); + Position target = Position.of("c5"); + + Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("퀸의 좌 하단 대각 이동") + @Test + void leftDownTest() { + Position source = Position.of("g7"); + Position target = Position.of("c3"); + + Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("퀸의 상단 직진 이동") + @Test + void upTest() { + Position source = Position.of("a1"); + Position target = Position.of("a6"); + + Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("퀸의 하단 직진 이동") + @Test + void downTest() { + Position source = Position.of("a6"); + Position target = Position.of("a1"); + + Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("퀸의 우측 직진 이동") + @Test + void rightTest() { + Position source = Position.of("a1"); + Position target = Position.of("g1"); + + Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("퀸의 좌측 직진 이동") + @Test + void leftTest() { + Position source = Position.of("g1"); + Position target = Position.of("a1"); + + Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("타겟 위치에 적이 있을 때 이동") + @Test + void moveWhenEnemyTest() { + Piece queen = new Piece(PieceType.QUEEN, Team.BLACK); + Piece enemy = new Piece(PieceType.PAWN, Team.WHITE); + Position source = Position.of("a1"); + Position target = Position.of("a6"); + Map enemyEntry = new HashMap<>(); + enemyEntry.put(source, queen); + enemyEntry.put(target, enemy); + Board enemyBoard = new Board(enemyEntry); + + Assertions.assertThat(queenStrategy.movable(source, target, enemyBoard)).isTrue(); + } +} diff --git a/src/test/java/chess/domain/strategy/move/RookMoveStrategyTest.java b/src/test/java/chess/domain/strategy/move/RookMoveStrategyTest.java new file mode 100644 index 00000000000..bf977aa2c90 --- /dev/null +++ b/src/test/java/chess/domain/strategy/move/RookMoveStrategyTest.java @@ -0,0 +1,77 @@ +package chess.domain.strategy.move; + +import chess.domain.board.Board; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceType; +import chess.domain.piece.Team; +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +public class RookMoveStrategyTest { + private MoveStrategy rookStrategy; + private Board board; + + @BeforeEach + private void setUp() { + rookStrategy = new RookMoveStrategy(); + Map emptyBoard = new HashMap<>(); + board = new Board(emptyBoard); + } + + @DisplayName("룩의 상단 직진 이동") + @Test + void upTest() { + Position source = Position.of("a1"); + Position target = Position.of("a6"); + + Assertions.assertThat(rookStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("룩의 하단 직진 이동") + @Test + void downTest() { + Position source = Position.of("a6"); + Position target = Position.of("a1"); + + Assertions.assertThat(rookStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("룩의 우측 직진 이동") + @Test + void rightTest() { + Position source = Position.of("a1"); + Position target = Position.of("g1"); + + Assertions.assertThat(rookStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("룩의 좌측 직진 이동") + @Test + void leftTest() { + Position source = Position.of("g1"); + Position target = Position.of("a1"); + + Assertions.assertThat(rookStrategy.movable(source, target, board)).isTrue(); + } + + @DisplayName("타겟 위치에 적이 있을 때 이동 테스트") + @Test + void moveWhenEnemyTest() { + Piece rook = new Piece(PieceType.ROOK, Team.BLACK); + Piece enemy = new Piece(PieceType.PAWN, Team.WHITE); + Position source = Position.of("a1"); + Position target = Position.of("a6"); + Map enemyEntry = new HashMap<>(); + enemyEntry.put(source, rook); + enemyEntry.put(target, enemy); + Board enemyBoard = new Board(enemyEntry); + + Assertions.assertThat(rookStrategy.movable(source, target, enemyBoard)).isTrue(); + } +} diff --git a/src/test/java/chess/domain/strategy/move/direction/DirectionTest.java b/src/test/java/chess/domain/strategy/move/direction/DirectionTest.java index 778ade7f67a..6e099801ded 100644 --- a/src/test/java/chess/domain/strategy/move/direction/DirectionTest.java +++ b/src/test/java/chess/domain/strategy/move/direction/DirectionTest.java @@ -1,12 +1,73 @@ package chess.domain.strategy.move.direction; +import chess.domain.position.Position; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; + public class DirectionTest { - @DisplayName("조건에 맞는 방향 반환") + @DisplayName("위 방향 이동") + @Test + void checkUpStrategy() { + Position source = Position.of("a1"); + Position target = Position.of("a8"); + assertThat(Direction.findDirection(source, target)).isEqualTo(Direction.UP); + } + + @DisplayName("아래 방향 이동") @Test - void findTest() { + void checkDownStrategy() { + Position source = Position.of("a8"); + Position target = Position.of("a1"); + assertThat(Direction.findDirection(source, target)).isEqualTo(Direction.DOWN); + } + + @DisplayName("왼쪽 방향 이동") + @Test + void checkLeftStrategy() { + Position source = Position.of("e5"); + Position target = Position.of("b5"); + assertThat(Direction.findDirection(source, target)).isEqualTo(Direction.LEFT); + } + + @DisplayName("오른쪽 방향 이동") + @Test + void checkRightStrategy() { + Position source = Position.of("b5"); + Position target = Position.of("e5"); + assertThat(Direction.findDirection(source, target)).isEqualTo(Direction.RIGHT); + } + @DisplayName("왼쪽 위 방향 이동") + @Test + void checkLeftUpStrategy() { + Position source = Position.of("e1"); + Position target = Position.of("c3"); + assertThat(Direction.findDirection(source, target)).isEqualTo(Direction.LEFT_UP); + } + + @DisplayName("왼쪽 아래 방향 이동") + @Test + void checkLeftDownStrategy() { + Position source = Position.of("h8"); + Position target = Position.of("a1"); + assertThat(Direction.findDirection(source, target)).isEqualTo(Direction.LEFT_DOWN); + } + + @DisplayName("오른쪽 위 방향 이동") + @Test + void checkRightUpStrategy() { + Position source = Position.of("a1"); + Position target = Position.of("h8"); + assertThat(Direction.findDirection(source, target)).isEqualTo(Direction.RIGHT_UP); + } + + @DisplayName("오른쪽 아래 방향 이동") + @Test + void checkRightDownStrategy() { + Position source = Position.of("a8"); + Position target = Position.of("e1"); + assertThat(Direction.findDirection(source, target)).isEqualTo(Direction.RIGHT_DOWN); } -} +} \ No newline at end of file From db9009f88f07f7890120dabdfaeb3d504761dbc5 Mon Sep 17 00:00:00 2001 From: giantim Date: Sat, 28 Mar 2020 12:07:33 +0900 Subject: [PATCH 20/29] =?UTF-8?q?refactor:=20=EB=B3=80=EA=B2=BD=EB=90=98?= =?UTF-8?q?=EB=A9=B4=20=EC=95=88=EB=90=98=EB=8A=94=20=EB=A7=A4=EA=B0=9C=20?= =?UTF-8?q?=EB=B3=80=EC=88=98,=20=ED=81=B4=EB=9E=98=EC=8A=A4=EC=97=90=20fi?= =?UTF-8?q?nal=20=ED=82=A4=EC=9B=8C=EB=93=9C=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chess/controller/ChessController.java | 4 +-- src/main/java/chess/domain/board/Board.java | 30 +++++++++---------- src/main/java/chess/domain/piece/Piece.java | 6 ++-- .../java/chess/domain/piece/PieceType.java | 2 +- src/main/java/chess/domain/piece/Team.java | 4 +-- src/main/java/chess/domain/position/File.java | 4 +-- .../java/chess/domain/position/Position.java | 7 ++--- src/main/java/chess/domain/position/Rank.java | 12 ++++---- .../strategy/move/BishopMoveStrategy.java | 5 ++-- .../strategy/move/KingMoveStrategy.java | 5 ++-- .../strategy/move/KnightMoveStrategy.java | 4 +-- .../domain/strategy/move/MoveStrategy.java | 9 +++--- .../strategy/move/PawnMoveStrategy.java | 4 +-- .../strategy/move/QueenMoveStrategy.java | 5 ++-- .../strategy/move/RookMoveStrategy.java | 4 +-- .../strategy/move/direction/Direction.java | 9 +++--- .../strategy/move/direction/DownStrategy.java | 4 +-- .../move/direction/LeftDownStrategy.java | 4 +-- .../strategy/move/direction/LeftStrategy.java | 4 +-- .../move/direction/LeftUpStrategy.java | 4 +-- .../move/direction/RightDownStrategy.java | 4 +-- .../move/direction/RightStrategy.java | 4 +-- .../move/direction/RightUpStrategy.java | 4 +-- .../strategy/move/direction/UpStrategy.java | 4 +-- 24 files changed, 71 insertions(+), 75 deletions(-) diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index 7488488f82d..fdf6c94e972 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -48,7 +48,7 @@ public static void run() { } } - private static boolean findWinner(ChessRunner chessRunner) { + private static boolean findWinner(final ChessRunner chessRunner) { Team winner = chessRunner.findWinner(); if (winner != null) { outputView.printWinner(winner); @@ -57,7 +57,7 @@ private static boolean findWinner(ChessRunner chessRunner) { return true; } - private static void printBoard(Board board) { + private static void printBoard(final Board board) { BoardDto boardDto = new BoardDto(board.parse()); PositionDto positionDto = new PositionDto(Position.getPositions()); outputView.printBoard(positionDto.getPositions(), boardDto.get()); diff --git a/src/main/java/chess/domain/board/Board.java b/src/main/java/chess/domain/board/Board.java index c685bab6c97..d42f958b544 100644 --- a/src/main/java/chess/domain/board/Board.java +++ b/src/main/java/chess/domain/board/Board.java @@ -12,13 +12,16 @@ import java.util.stream.Collectors; public class Board { + private static final int PAWN_ON_SAME_FILE = 1; + private static final double PAWN_SCORE_STRATEGY = 0.5; + private final Map board; public Board() { this(BoardInitializer.initializeAll()); } - public Board(Map board) { + public Board(final Map board) { this.board = board; } @@ -28,10 +31,11 @@ public Map parse() { .collect(Collectors.toMap(entry -> entry.getKey().toString(), entry -> entry.getValue().toSymbol(), (e1, e2) -> e1, LinkedHashMap::new)); + return Collections.unmodifiableMap(parseResult); } - public void updateBoard(Position sourcePosition, Position targetPosition) { + public void updateBoard(final Position sourcePosition, final Position targetPosition) { Piece selectedPiece = this.board.get(sourcePosition); this.board.put(targetPosition, selectedPiece); this.board.remove(sourcePosition); @@ -48,17 +52,13 @@ public Team checkWinner() { } private boolean checkWhiteKing() { - for (Piece piece : board.values()) { - if (piece.isWhiteKing()) return true; - } - return false; + return this.board.values().stream() + .anyMatch(Piece::isWhiteKing); } private boolean checkBlackKing() { - for (Piece piece : board.values()) { - if (piece.isBlackKing()) return true; - } - return false; + return this.board.values().stream() + .anyMatch(Piece::isBlackKing); } public boolean isEmpty(final Position position) { @@ -69,27 +69,27 @@ public Piece getPiece(final Position position) { return this.board.get(position); } - public double calculateScore(Team team) { + public double calculateScore(final Team team) { double totalScore = calculateTotalScore(team); return calculatePawnScore(team, totalScore); } - private double calculateTotalScore(Team team) { + private double calculateTotalScore(final Team team) { return board.values().stream() .filter(piece -> team.isSameTeamWith(piece.getTeam())) .mapToDouble(Piece::getScore) .sum(); } - private double calculatePawnScore(Team team, double score) { + private double calculatePawnScore(final Team team, double score) { for (File file : File.values()) { List> sameFile = this.board.entrySet().stream() .filter(entry -> File.of(entry.getKey().getFile()).equals(file)) .filter(entry -> entry.getValue().isPawn() && !entry.getValue().isEnemy(team)) .collect(Collectors.toList()); - if (sameFile.size() > 1) { - score -= sameFile.size() * 0.5; + if (sameFile.size() > PAWN_ON_SAME_FILE) { + score -= sameFile.size() * PAWN_SCORE_STRATEGY; } } return score; diff --git a/src/main/java/chess/domain/piece/Piece.java b/src/main/java/chess/domain/piece/Piece.java index 72b62745474..5169eb6c99c 100644 --- a/src/main/java/chess/domain/piece/Piece.java +++ b/src/main/java/chess/domain/piece/Piece.java @@ -16,15 +16,15 @@ public String toSymbol() { return this.team.symbolize(this.pieceType.getSymbol()); } - public boolean movable(Position source, Position target, Board board) { + public boolean movable(final Position source, final Position target, final Board board) { return this.pieceType.movable(source, target, board); } - public boolean isEnemy(Piece targetPiece) { + public boolean isEnemy(final Piece targetPiece) { return !this.team.isSameTeamWith(targetPiece.getTeam()); } - public boolean isEnemy(Team team) { + public boolean isEnemy(final Team team) { return !this.team.isSameTeamWith(team); } diff --git a/src/main/java/chess/domain/piece/PieceType.java b/src/main/java/chess/domain/piece/PieceType.java index f14a48d6022..f50f5efc873 100644 --- a/src/main/java/chess/domain/piece/PieceType.java +++ b/src/main/java/chess/domain/piece/PieceType.java @@ -22,7 +22,7 @@ public enum PieceType { this.moveStrategy = moveStrategy; } - public boolean movable(Position source, Position target, Board board) { + public boolean movable(final Position source, final Position target, final Board board) { return this.moveStrategy.movable(source, target, board); } diff --git a/src/main/java/chess/domain/piece/Team.java b/src/main/java/chess/domain/piece/Team.java index 8b7d025abe0..6ae03e8124d 100644 --- a/src/main/java/chess/domain/piece/Team.java +++ b/src/main/java/chess/domain/piece/Team.java @@ -12,7 +12,7 @@ public enum Team { this.expression = expression; } - public static Team changeTeam(Team team) { + public static Team changeTeam(final Team team) { if (team == BLACK) { return WHITE; } @@ -23,7 +23,7 @@ public String symbolize(final String name) { return this.expression.apply(name); } - public boolean isSameTeamWith(Team team) { + public boolean isSameTeamWith(final Team team) { return this == team; } diff --git a/src/main/java/chess/domain/position/File.java b/src/main/java/chess/domain/position/File.java index 29f6ad3747a..bb03d1216d0 100644 --- a/src/main/java/chess/domain/position/File.java +++ b/src/main/java/chess/domain/position/File.java @@ -20,14 +20,14 @@ public enum File { this.number = number; } - public static File of(String file) { + public static File of(final String file) { return Arrays.stream(values()) .filter(f -> f.symbol == file.toLowerCase().charAt(0)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("잘못된 x 좌표값을 입력하였습니다.")); } - public static File of(int file) { + public static File of(final int file) { return Arrays.stream(values()) .filter(f -> f.number == file) .findFirst() diff --git a/src/main/java/chess/domain/position/Position.java b/src/main/java/chess/domain/position/Position.java index ac8a76b63e4..4ba4ddb7fd5 100644 --- a/src/main/java/chess/domain/position/Position.java +++ b/src/main/java/chess/domain/position/Position.java @@ -59,12 +59,11 @@ public static List getPositions() { return Collections.unmodifiableList(parseResult); } - public int calculateFileGap(Position target) { - int fileGap = this.file.compareTo(target.file); - return fileGap; + public int calculateFileGap(final Position target) { + return this.file.compareTo(target.file); } - public int calculateRankGap(Position target) { + public int calculateRankGap(final Position target) { return this.rank.getDifference(target.rank); } diff --git a/src/main/java/chess/domain/position/Rank.java b/src/main/java/chess/domain/position/Rank.java index f1034ef6464..002a9c69536 100644 --- a/src/main/java/chess/domain/position/Rank.java +++ b/src/main/java/chess/domain/position/Rank.java @@ -18,25 +18,25 @@ public enum Rank { this.symbol = symbol; } - public static Rank of(String rank) { + public static Rank of(final String rank) { return Arrays.stream(values()) .filter(pv -> pv.symbol == Integer.parseInt(rank)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("잘못된 y 좌표값을 입력하였습니다.")); } - public static Rank of(int rank) { + public static Rank of(final int rank) { return Arrays.stream(values()) .filter(f -> f.symbol == rank) .findFirst() .orElseThrow(() -> new IllegalArgumentException("잘못된 y 좌표값을 입력하였습니다.")); } - public int getSymbol() { - return this.symbol; + public int getDifference(final Rank rank) { + return this.symbol - rank.symbol; } - public int getDifference(Rank rank) { - return this.symbol - rank.symbol; + public int getSymbol() { + return this.symbol; } } diff --git a/src/main/java/chess/domain/strategy/move/BishopMoveStrategy.java b/src/main/java/chess/domain/strategy/move/BishopMoveStrategy.java index 60fc5310997..2d6b99cda57 100644 --- a/src/main/java/chess/domain/strategy/move/BishopMoveStrategy.java +++ b/src/main/java/chess/domain/strategy/move/BishopMoveStrategy.java @@ -3,10 +3,9 @@ import chess.domain.board.Board; import chess.domain.position.Position; -public class BishopMoveStrategy extends MoveStrategy { - +public final class BishopMoveStrategy extends MoveStrategy { @Override - public boolean movable(Position source, Position target, Board board) { + public boolean movable(final Position source, final Position target, final Board board) { if (isSamePosition(source, target)) { return false; } diff --git a/src/main/java/chess/domain/strategy/move/KingMoveStrategy.java b/src/main/java/chess/domain/strategy/move/KingMoveStrategy.java index 86893b86e6b..1b7c157e9e1 100644 --- a/src/main/java/chess/domain/strategy/move/KingMoveStrategy.java +++ b/src/main/java/chess/domain/strategy/move/KingMoveStrategy.java @@ -3,10 +3,9 @@ import chess.domain.board.Board; import chess.domain.position.Position; -public class KingMoveStrategy extends MoveStrategy { - +public final class KingMoveStrategy extends MoveStrategy { @Override - public boolean movable(Position source, Position target, Board board) { + public boolean movable(final Position source, final Position target, final Board board) { if (isSamePosition(source, target)) { return false; } diff --git a/src/main/java/chess/domain/strategy/move/KnightMoveStrategy.java b/src/main/java/chess/domain/strategy/move/KnightMoveStrategy.java index 6a7582c9bbb..7a2e2676256 100644 --- a/src/main/java/chess/domain/strategy/move/KnightMoveStrategy.java +++ b/src/main/java/chess/domain/strategy/move/KnightMoveStrategy.java @@ -3,9 +3,9 @@ import chess.domain.board.Board; import chess.domain.position.Position; -public class KnightMoveStrategy extends MoveStrategy { +public final class KnightMoveStrategy extends MoveStrategy { @Override - public boolean movable(Position source, Position target, Board board) { + public boolean movable(final Position source, final Position target, final Board board) { if (isSamePosition(source, target)) { return false; } diff --git a/src/main/java/chess/domain/strategy/move/MoveStrategy.java b/src/main/java/chess/domain/strategy/move/MoveStrategy.java index 27ea9af6e81..5b6395ce053 100644 --- a/src/main/java/chess/domain/strategy/move/MoveStrategy.java +++ b/src/main/java/chess/domain/strategy/move/MoveStrategy.java @@ -8,12 +8,11 @@ import java.util.List; public abstract class MoveStrategy { - - protected boolean isSamePosition(Position source, Position target) { + protected boolean isSamePosition(final Position source, final Position target) { return source.equals(target); } - protected boolean checkObstacle(Position source, Position target, Board board) { + protected boolean checkObstacle(final Position source, final Position target, final Board board) { Direction direction = Direction.findDirection(source, target); List path = direction.findPath(source, target); @@ -21,7 +20,7 @@ protected boolean checkObstacle(Position source, Position target, Board board) { .allMatch(board::isEmpty); } - protected boolean checkTarget(Position source, Position target, Board board) { + protected boolean checkTarget(final Position source, final Position target, final Board board) { Piece sourcePiece = board.getPiece(source); if (board.isEmpty(target)) { return true; @@ -30,5 +29,5 @@ protected boolean checkTarget(Position source, Position target, Board board) { return sourcePiece.isEnemy(targetPiece); } - public abstract boolean movable(Position source, Position target, Board board); + public abstract boolean movable(final Position source, final Position target, final Board board); } diff --git a/src/main/java/chess/domain/strategy/move/PawnMoveStrategy.java b/src/main/java/chess/domain/strategy/move/PawnMoveStrategy.java index ab116760b22..51152f41ea2 100644 --- a/src/main/java/chess/domain/strategy/move/PawnMoveStrategy.java +++ b/src/main/java/chess/domain/strategy/move/PawnMoveStrategy.java @@ -5,12 +5,12 @@ import chess.domain.piece.Team; import chess.domain.position.Position; -public class PawnMoveStrategy extends MoveStrategy { +public final class PawnMoveStrategy extends MoveStrategy { private static final int WHITE_POSITION = 2; private static final int BLACK_POSITION = 7; @Override - public boolean movable(Position source, Position target, Board board) { + public boolean movable(final Position source, final Position target, final Board board) { if (isSamePosition(source, target)) { return false; } diff --git a/src/main/java/chess/domain/strategy/move/QueenMoveStrategy.java b/src/main/java/chess/domain/strategy/move/QueenMoveStrategy.java index 4a8f9dbbd6f..06b05f8db8b 100644 --- a/src/main/java/chess/domain/strategy/move/QueenMoveStrategy.java +++ b/src/main/java/chess/domain/strategy/move/QueenMoveStrategy.java @@ -3,10 +3,9 @@ import chess.domain.board.Board; import chess.domain.position.Position; -public class QueenMoveStrategy extends MoveStrategy { - +public final class QueenMoveStrategy extends MoveStrategy { @Override - public boolean movable(Position source, Position target, Board board) { + public boolean movable(final Position source, final Position target, final Board board) { return new RookMoveStrategy().movable(source, target, board) || new BishopMoveStrategy().movable(source, target, board); } diff --git a/src/main/java/chess/domain/strategy/move/RookMoveStrategy.java b/src/main/java/chess/domain/strategy/move/RookMoveStrategy.java index 6b46d56f9a0..91f0bc112c3 100644 --- a/src/main/java/chess/domain/strategy/move/RookMoveStrategy.java +++ b/src/main/java/chess/domain/strategy/move/RookMoveStrategy.java @@ -3,9 +3,9 @@ import chess.domain.board.Board; import chess.domain.position.Position; -public class RookMoveStrategy extends MoveStrategy { +public final class RookMoveStrategy extends MoveStrategy { @Override - public boolean movable(Position source, Position target, Board board) { + public boolean movable(final Position source, final Position target, final Board board) { if (isSamePosition(source, target)) { return false; } diff --git a/src/main/java/chess/domain/strategy/move/direction/Direction.java b/src/main/java/chess/domain/strategy/move/direction/Direction.java index 48301427d30..857ad66d9a7 100644 --- a/src/main/java/chess/domain/strategy/move/direction/Direction.java +++ b/src/main/java/chess/domain/strategy/move/direction/Direction.java @@ -16,24 +16,25 @@ public enum Direction { RIGHT_UP(new RightUpStrategy(), (fileGap, rankGap) -> fileGap > 0 && rankGap > 0), RIGHT_DOWN(new RightDownStrategy(), (fileGap, rankGap) -> fileGap > 0 && rankGap < 0); - private DirectionStrategy directionStrategy; - private BiPredicate condition; + private final DirectionStrategy directionStrategy; + private final BiPredicate condition; Direction(DirectionStrategy directionStrategy, BiPredicate condition) { this.directionStrategy = directionStrategy; this.condition = condition; } - public static Direction findDirection(Position source, Position target) { + public static Direction findDirection(final Position source, final Position target) { int fileGap = target.calculateFileGap(source); int rankGap = target.calculateRankGap(source); + return Arrays.stream(values()) .filter(direction -> direction.condition.test(fileGap, rankGap)) .findFirst() .orElseThrow(AssertionError::new); } - public List findPath(Position source, Position target) { + public List findPath(final Position source, final Position target) { return this.directionStrategy.findPath(source, target); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java b/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java index d7d62a77070..182db434310 100644 --- a/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java @@ -5,9 +5,9 @@ import java.util.ArrayList; import java.util.List; -public class DownStrategy implements DirectionStrategy { +public final class DownStrategy implements DirectionStrategy { @Override - public List findPath(Position source, Position target) { + public List findPath(final Position source, final Position target) { List path = new ArrayList<>(); for (int i = target.getRank() + 1; i < source.getRank(); i++) { diff --git a/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java b/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java index f6aecaba9d9..0c882279e8d 100644 --- a/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java @@ -5,10 +5,10 @@ import java.util.ArrayList; import java.util.List; -public class LeftDownStrategy implements DirectionStrategy { +public final class LeftDownStrategy implements DirectionStrategy { @Override - public List findPath(Position source, Position target) { + public List findPath(final Position source, final Position target) { List path = new ArrayList<>(); for (int i = target.getFile() + 1; i < source.getFile(); i++) { diff --git a/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java b/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java index 53fed6f5394..b5a6caa750b 100644 --- a/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java @@ -5,9 +5,9 @@ import java.util.ArrayList; import java.util.List; -public class LeftStrategy implements DirectionStrategy { +public final class LeftStrategy implements DirectionStrategy { @Override - public List findPath(Position source, Position target) { + public List findPath(final Position source, final Position target) { List path = new ArrayList<>(); for (int i = target.getFile() + 1; i < source.getFile(); i++) { diff --git a/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java b/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java index 20842f29f74..d3313f7e5a9 100644 --- a/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java @@ -5,9 +5,9 @@ import java.util.ArrayList; import java.util.List; -public class LeftUpStrategy implements DirectionStrategy { +public final class LeftUpStrategy implements DirectionStrategy { @Override - public List findPath(Position source, Position target) { + public List findPath(final Position source, final Position target) { List path = new ArrayList<>(); for (int i = target.getFile() + 1; i < source.getFile(); i++) { diff --git a/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java b/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java index d5919f032e8..5551b9af7ff 100644 --- a/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java @@ -5,10 +5,10 @@ import java.util.ArrayList; import java.util.List; -public class RightDownStrategy implements DirectionStrategy { +public final class RightDownStrategy implements DirectionStrategy { @Override - public List findPath(Position source, Position target) { + public List findPath(final Position source, final Position target) { List path = new ArrayList<>(); for (int i = target.getFile() - 1; i > source.getFile(); i--) { diff --git a/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java b/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java index 2ce164b797c..4dc81307ff7 100644 --- a/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java @@ -5,9 +5,9 @@ import java.util.ArrayList; import java.util.List; -public class RightStrategy implements DirectionStrategy { +public final class RightStrategy implements DirectionStrategy { @Override - public List findPath(Position source, Position target) { + public List findPath(final Position source, final Position target) { List path = new ArrayList<>(); for (int i = target.getFile() - 1; i > source.getFile(); i--) { diff --git a/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java b/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java index ce7a9472f12..c518116fe6c 100644 --- a/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java @@ -5,10 +5,10 @@ import java.util.ArrayList; import java.util.List; -public class RightUpStrategy implements DirectionStrategy { +public final class RightUpStrategy implements DirectionStrategy { @Override - public List findPath(Position source, Position target) { + public List findPath(final Position source, final Position target) { List path = new ArrayList<>(); for (int i = target.getFile() - 1; i > source.getFile(); i--) { diff --git a/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java b/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java index 9728fdc2e8f..a4afb7f27b5 100644 --- a/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java @@ -5,9 +5,9 @@ import java.util.ArrayList; import java.util.List; -public class UpStrategy implements DirectionStrategy { +public final class UpStrategy implements DirectionStrategy { @Override - public List findPath(Position source, Position target) { + public List findPath(final Position source, final Position target) { List path = new ArrayList<>(); for (int i = target.getRank() - 1; i > source.getRank(); i--) { From fd4d688ecce35c708b3dc6fef22c29c0cf296014 Mon Sep 17 00:00:00 2001 From: giantim Date: Sat, 28 Mar 2020 15:08:51 +0900 Subject: [PATCH 21/29] =?UTF-8?q?refactor:=20=EC=BB=A8=ED=8A=B8=EB=A1=A4?= =?UTF-8?q?=EB=9F=AC=EC=9D=98=20=EC=8B=A4=ED=96=89=20=EB=A9=94=EC=84=9C?= =?UTF-8?q?=EB=93=9C=EB=A5=BC=20=EB=AA=85=EB=A0=B9=EC=96=B4=20=EB=B3=84?= =?UTF-8?q?=EB=A1=9C=20=EB=B6=84=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chess/controller/ChessController.java | 81 +++++++++++++------ src/main/java/chess/controller/Command.java | 27 +++++++ .../java/chess/view/ConsoleInputView.java | 40 +-------- .../java/chess/view/ConsoleOutputView.java | 9 ++- src/main/java/chess/view/InputView.java | 6 +- src/main/java/chess/view/OutputView.java | 4 +- 6 files changed, 96 insertions(+), 71 deletions(-) create mode 100644 src/main/java/chess/controller/Command.java diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index fdf6c94e972..81c2c1da8e5 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -12,39 +12,65 @@ import chess.view.OutputView; public class ChessController { + private static final String DELIMITER = " "; + private static final int SOURCE_INDEX = 1; + private static final int TARGET_INDEX = 2; + private static InputView inputView = new ConsoleInputView(); private static OutputView outputView = new ConsoleOutputView(); public static void start() { - if (inputView.askChessRun()) { - run(); + try { + Command command = Command.of(inputView.askChessRun()); + run(command); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + start(); } } - public static void run() { - ChessRunner chessRunner = new ChessRunner(); - printBoard(chessRunner.getBoard()); - boolean moveFlag = true; + private static void run(Command command) { + if (command.isStart()) { + ChessRunner chessRunner = new ChessRunner(); + printBoard(chessRunner.getBoard()); + runChess(chessRunner); + } + } + + public static void runChess(ChessRunner chessRunner) { + try { + String input = inputView.askGameCommand(); + Command command = Command.of(input); + + runByCommand(chessRunner, input, command); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + runChess(chessRunner); + } + } - while (moveFlag) { - try { - String[] moveSource = inputView.askMoveOrStatus().split(" "); - if (moveSource[0].toUpperCase().equals("END")) { - break; - } - if (moveSource[0].toUpperCase().equals("STATUS")) { - outputView.printStatus(chessRunner.calculateScore(), chessRunner.getCurrentTeam()); - continue; - } - String sourcePosition = moveSource[1]; - String targetPosition = moveSource[2]; - chessRunner.update(sourcePosition, targetPosition); - printBoard(chessRunner.getBoard()); - if (!findWinner(chessRunner)) break; + private static void runByCommand(ChessRunner chessRunner, String input, Command command) { + switch (command) { + case MOVE: + runMove(chessRunner, input); + break; + case STATUS: + runStatus(chessRunner); + break; + case END: + default: + break; + } + } - } catch (IllegalArgumentException e) { - System.out.println(e.getMessage()); - } + private static void runMove(ChessRunner chessRunner, String input) { + String[] commands = input.split(DELIMITER); + String source = commands[SOURCE_INDEX]; + String target = commands[TARGET_INDEX]; + chessRunner.update(source, target); + printBoard(chessRunner.getBoard()); + if (findWinner(chessRunner)) { + runChess(chessRunner); } } @@ -57,6 +83,13 @@ private static boolean findWinner(final ChessRunner chessRunner) { return true; } + private static void runStatus(ChessRunner chessRunner) { + double score = chessRunner.calculateScore(); + outputView.printStatus(score, chessRunner.getCurrentTeam()); + printBoard(chessRunner.getBoard()); + runChess(chessRunner); + } + private static void printBoard(final Board board) { BoardDto boardDto = new BoardDto(board.parse()); PositionDto positionDto = new PositionDto(Position.getPositions()); diff --git a/src/main/java/chess/controller/Command.java b/src/main/java/chess/controller/Command.java new file mode 100644 index 00000000000..b8585d45382 --- /dev/null +++ b/src/main/java/chess/controller/Command.java @@ -0,0 +1,27 @@ +package chess.controller; + +import java.util.Arrays; + +public enum Command { + START("start"), + MOVE("move"), + STATUS("status"), + END("end"); + + private String command; + + Command(String command) { + this.command = command; + } + + public static Command of(final String command) { + return Arrays.stream(values()) + .filter(c -> command.contains(c.command)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("잘못된 명령어를 입력하였습니다.")); + } + + public boolean isStart() { + return this == START; + } +} diff --git a/src/main/java/chess/view/ConsoleInputView.java b/src/main/java/chess/view/ConsoleInputView.java index 89b07e3f2a4..caf9c36fe07 100644 --- a/src/main/java/chess/view/ConsoleInputView.java +++ b/src/main/java/chess/view/ConsoleInputView.java @@ -4,50 +4,18 @@ public class ConsoleInputView implements InputView { private static final Scanner SCANNER = new Scanner(System.in); - private static final String START_COMMAND = "start"; - private static final String END_COMMAND = "end"; @Override - public boolean askChessRun() { + public String askChessRun() { System.out.println("> 체스 게임을 시작합니다."); System.out.println("> 게임 시작 : start"); System.out.println("> 게임 종료 : end"); System.out.println("> 게임 이동 : move source위치 target위치 - 예. move b2 b3"); - try { - String input = SCANNER.nextLine(); - validateRunCommand(input); - return runFlag(input); - } catch (IllegalArgumentException e) { - System.out.println(e.getMessage()); - return askChessRun(); - } - } - - private void validateRunCommand(String input) { - if (!input.equals(START_COMMAND) && !input.equals(END_COMMAND)) { - throw new IllegalArgumentException("start 또는 end 를 입력해주세요."); - } - } - - private boolean runFlag(String input) { - return input.equals(START_COMMAND); + return askGameCommand(); } @Override - public String askMoveOrStatus() { - try { - String input = SCANNER.nextLine(); - validateMove(input); - return input; - } catch (IllegalArgumentException e) { - System.out.println(e.getMessage()); - return askMoveOrStatus(); - } - } - - private static void validateMove(String input) { - if (!input.contains("move") && !input.equals("status") && !input.equals("end")) { - throw new IllegalArgumentException("잘못된 명령어를 입력하였습니다."); - } + public String askGameCommand() { + return SCANNER.nextLine(); } } diff --git a/src/main/java/chess/view/ConsoleOutputView.java b/src/main/java/chess/view/ConsoleOutputView.java index b6326a5d503..b0cc85985cd 100644 --- a/src/main/java/chess/view/ConsoleOutputView.java +++ b/src/main/java/chess/view/ConsoleOutputView.java @@ -16,6 +16,7 @@ public void printBoard(final List positions, final Map b System.out.print(printPiece(piece)); checkNewLine(i); } + System.out.println(); } private void checkNewLine(final int i) { @@ -32,12 +33,12 @@ private String printPiece(String piece) { } @Override - public void printWinner(Team team) { - System.out.println(String.format("%s 팀이 이겼습니다.", team.name())); + public void printStatus(double calculateScore, Team team) { + System.out.println(String.format("%s 팀의 점수는 %.1f 점입니다.", team.name(), calculateScore)); } @Override - public void printStatus(double calculateScore, Team team) { - System.out.println(String.format("%s 팀의 점수는 %.1f 점입니다.", team.name(), calculateScore)); + public void printWinner(Team team) { + System.out.println(String.format("%s 팀이 이겼습니다.", team.name())); } } diff --git a/src/main/java/chess/view/InputView.java b/src/main/java/chess/view/InputView.java index 01c2fb9df8f..adb656d5da3 100644 --- a/src/main/java/chess/view/InputView.java +++ b/src/main/java/chess/view/InputView.java @@ -1,8 +1,6 @@ package chess.view; public interface InputView { - - boolean askChessRun(); - - String askMoveOrStatus(); + String askChessRun(); + String askGameCommand(); } diff --git a/src/main/java/chess/view/OutputView.java b/src/main/java/chess/view/OutputView.java index 99cf6959ee1..1399b824401 100644 --- a/src/main/java/chess/view/OutputView.java +++ b/src/main/java/chess/view/OutputView.java @@ -7,8 +7,6 @@ public interface OutputView { void printBoard(List positions, Map board); - - void printWinner(Team team); - void printStatus(double calculateScore, Team team); + void printWinner(Team team); } From 6f154645366819aff1624a71bbf0966a1d3bec99 Mon Sep 17 00:00:00 2001 From: giantim Date: Sat, 28 Mar 2020 15:39:38 +0900 Subject: [PATCH 22/29] =?UTF-8?q?refactor:=20DirectionStrategy=20=EC=9D=98?= =?UTF-8?q?=20=EA=B5=AC=ED=98=84=20=ED=81=B4=EB=9E=98=EC=8A=A4=EB=93=A4?= =?UTF-8?q?=EC=9D=98=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94=EB=93=9C=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 --- .../strategy/move/direction/DownStrategy.java | 12 +++++---- .../move/direction/LeftDownStrategy.java | 17 +++++------- .../strategy/move/direction/LeftStrategy.java | 12 +++++---- .../move/direction/LeftUpStrategy.java | 15 ++++++----- .../move/direction/RightDownStrategy.java | 13 ++++----- .../move/direction/RightStrategy.java | 12 +++++---- .../move/direction/RightUpStrategy.java | 13 ++++----- .../strategy/move/direction/UpStrategy.java | 12 +++++---- .../move/direction/DownStrategyTest.java | 26 ++++++++++++++++++ .../move/direction/LeftDownStrategyTest.java | 26 ++++++++++++++++++ .../move/direction/LeftStrategyTest.java | 27 +++++++++++++++++++ .../move/direction/LeftUpStrategyTest.java | 26 ++++++++++++++++++ .../move/direction/RightDownStrategyTest.java | 26 ++++++++++++++++++ .../move/direction/RightStrategyTest.java | 26 ++++++++++++++++++ .../move/direction/RightUpStrategyTest.java | 26 ++++++++++++++++++ .../move/direction/UpStrategyTest.java | 26 ++++++++++++++++++ 16 files changed, 266 insertions(+), 49 deletions(-) create mode 100644 src/test/java/chess/domain/strategy/move/direction/DownStrategyTest.java create mode 100644 src/test/java/chess/domain/strategy/move/direction/LeftDownStrategyTest.java create mode 100644 src/test/java/chess/domain/strategy/move/direction/LeftStrategyTest.java create mode 100644 src/test/java/chess/domain/strategy/move/direction/LeftUpStrategyTest.java create mode 100644 src/test/java/chess/domain/strategy/move/direction/RightDownStrategyTest.java create mode 100644 src/test/java/chess/domain/strategy/move/direction/RightStrategyTest.java create mode 100644 src/test/java/chess/domain/strategy/move/direction/RightUpStrategyTest.java create mode 100644 src/test/java/chess/domain/strategy/move/direction/UpStrategyTest.java diff --git a/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java b/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java index 182db434310..9d0cae3a260 100644 --- a/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java @@ -3,16 +3,18 @@ import chess.domain.position.Position; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; public final class DownStrategy implements DirectionStrategy { @Override public List findPath(final Position source, final Position target) { - List path = new ArrayList<>(); + List path = IntStream.range(target.getRank() + 1, source.getRank()) + .mapToObj(index -> Position.of(source.getFile(), index)) + .collect(Collectors.toList()); - for (int i = target.getRank() + 1; i < source.getRank(); i++) { - path.add(Position.of(source.getFile(), i)); - } - return path; + return Collections.unmodifiableList(path); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java b/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java index 0c882279e8d..0b2927ebcfb 100644 --- a/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java @@ -3,22 +3,19 @@ import chess.domain.position.Position; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; public final class LeftDownStrategy implements DirectionStrategy { @Override public List findPath(final Position source, final Position target) { - List path = new ArrayList<>(); + List path = IntStream.range(target.getFile() + 1, source.getFile()) + .mapToObj(index -> Position.of(index, target.getRank() - (target.getFile() - index))) + .collect(Collectors.toList()); - for (int i = target.getFile() + 1; i < source.getFile(); i++) { - path.add(Position.of(i, target.getRank() - (target.getFile() - i))); - } - -// List path2 = IntStream.range(target.getFile() + 1, source.getFile()) -// .mapToObj(index -> Position.of(index, target.getRank() - (target.getFile() - index))) -// .collect(Collectors.toList()); - - return path; + return Collections.unmodifiableList(path); } } diff --git a/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java b/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java index b5a6caa750b..e95cbff9e82 100644 --- a/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java @@ -3,16 +3,18 @@ import chess.domain.position.Position; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; public final class LeftStrategy implements DirectionStrategy { @Override public List findPath(final Position source, final Position target) { - List path = new ArrayList<>(); + List path = IntStream.range(target.getFile() + 1, source.getFile()) + .mapToObj(index -> Position.of(index, source.getRank())) + .collect(Collectors.toList()); - for (int i = target.getFile() + 1; i < source.getFile(); i++) { - path.add(Position.of(i, source.getRank())); - } - return path; + return Collections.unmodifiableList(path); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java b/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java index d3313f7e5a9..03400dc3e29 100644 --- a/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java @@ -3,17 +3,18 @@ import chess.domain.position.Position; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; public final class LeftUpStrategy implements DirectionStrategy { @Override public List findPath(final Position source, final Position target) { - List path = new ArrayList<>(); - - for (int i = target.getFile() + 1; i < source.getFile(); i++) { - path.add(Position.of(i, target.getRank() + (target.getFile() - i))); - } - - return path; + List path = IntStream.range(target.getFile() + 1, source.getFile()) + .mapToObj(index -> Position.of(index, target.getRank() + (target.getFile() - index))) + .collect(Collectors.toList()); + + return Collections.unmodifiableList(path); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java b/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java index 5551b9af7ff..9a304efcfaa 100644 --- a/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java @@ -3,18 +3,19 @@ import chess.domain.position.Position; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; public final class RightDownStrategy implements DirectionStrategy { @Override public List findPath(final Position source, final Position target) { - List path = new ArrayList<>(); + List path = IntStream.rangeClosed(source.getFile() + 1, target.getFile() -1) + .mapToObj(index -> Position.of(index, target.getRank() + (target.getFile() - index))) + .collect(Collectors.toList()); - for (int i = target.getFile() - 1; i > source.getFile(); i--) { - path.add(Position.of(i, target.getRank() + (target.getFile() - i))); - } - - return path; + return Collections.unmodifiableList(path); } } diff --git a/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java b/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java index 4dc81307ff7..112de22e38f 100644 --- a/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java @@ -3,16 +3,18 @@ import chess.domain.position.Position; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; public final class RightStrategy implements DirectionStrategy { @Override public List findPath(final Position source, final Position target) { - List path = new ArrayList<>(); + List path = IntStream.rangeClosed(source.getFile() + 1, target.getFile() - 1) + .mapToObj(index -> Position.of(index, source.getRank())) + .collect(Collectors.toList()); - for (int i = target.getFile() - 1; i > source.getFile(); i--) { - path.add(Position.of(i, source.getRank())); - } - return path; + return Collections.unmodifiableList(path); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java b/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java index c518116fe6c..ffadef2983d 100644 --- a/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java @@ -3,18 +3,19 @@ import chess.domain.position.Position; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; public final class RightUpStrategy implements DirectionStrategy { @Override public List findPath(final Position source, final Position target) { - List path = new ArrayList<>(); + List path = IntStream.rangeClosed(source.getFile() + 1, target.getFile() - 1) + .mapToObj(index -> Position.of(index, target.getRank() - (target.getFile() - index))) + .collect(Collectors.toList()); - for (int i = target.getFile() - 1; i > source.getFile(); i--) { - path.add(Position.of(i, target.getRank() - (target.getFile() - i))); - } - - return path; + return Collections.unmodifiableList(path); } } diff --git a/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java b/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java index a4afb7f27b5..8c7e704a4a8 100644 --- a/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java +++ b/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java @@ -3,16 +3,18 @@ import chess.domain.position.Position; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; public final class UpStrategy implements DirectionStrategy { @Override public List findPath(final Position source, final Position target) { - List path = new ArrayList<>(); + List path = IntStream.rangeClosed(source.getRank() + 1, target.getRank() - 1) + .mapToObj(index -> Position.of(source.getFile(), index)) + .collect(Collectors.toList()); - for (int i = target.getRank() - 1; i > source.getRank(); i--) { - path.add(Position.of(source.getFile(), i)); - } - return path; + return Collections.unmodifiableList(path); } } \ No newline at end of file diff --git a/src/test/java/chess/domain/strategy/move/direction/DownStrategyTest.java b/src/test/java/chess/domain/strategy/move/direction/DownStrategyTest.java new file mode 100644 index 00000000000..60eea0efeb5 --- /dev/null +++ b/src/test/java/chess/domain/strategy/move/direction/DownStrategyTest.java @@ -0,0 +1,26 @@ +package chess.domain.strategy.move.direction; + +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +public class DownStrategyTest { + @DisplayName("하단 이동 시 경로 구하기") + @Test + void findPathTest() { + DirectionStrategy directionStrategy = new DownStrategy(); + Position source = Position.of("a7"); + Position target = Position.of("a2"); + List path = directionStrategy.findPath(source, target); + + Assertions.assertThat(path).containsExactly( + Position.of("a3"), + Position.of("a4"), + Position.of("a5"), + Position.of("a6") + ); + } +} diff --git a/src/test/java/chess/domain/strategy/move/direction/LeftDownStrategyTest.java b/src/test/java/chess/domain/strategy/move/direction/LeftDownStrategyTest.java new file mode 100644 index 00000000000..7b0ccb44a14 --- /dev/null +++ b/src/test/java/chess/domain/strategy/move/direction/LeftDownStrategyTest.java @@ -0,0 +1,26 @@ +package chess.domain.strategy.move.direction; + +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +public class LeftDownStrategyTest { + @DisplayName("좌측 하단 이동 시 경로 구하기") + @Test + void findPathTest() { + DirectionStrategy directionStrategy = new LeftDownStrategy(); + Position source = Position.of("g7"); + Position target = Position.of("b2"); + List path = directionStrategy.findPath(source, target); + + Assertions.assertThat(path).containsExactly( + Position.of("c3"), + Position.of("d4"), + Position.of("e5"), + Position.of("f6") + ); + } +} diff --git a/src/test/java/chess/domain/strategy/move/direction/LeftStrategyTest.java b/src/test/java/chess/domain/strategy/move/direction/LeftStrategyTest.java new file mode 100644 index 00000000000..8b27066e7f4 --- /dev/null +++ b/src/test/java/chess/domain/strategy/move/direction/LeftStrategyTest.java @@ -0,0 +1,27 @@ +package chess.domain.strategy.move.direction; + +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +public class LeftStrategyTest { + @DisplayName("좌측 이동 시 경로 구하기") + @Test + void findPathTest() { + DirectionStrategy directionStrategy = new LeftStrategy(); + Position source = Position.of("g2"); + Position target = Position.of("a2"); + List path = directionStrategy.findPath(source, target); + + Assertions.assertThat(path).containsExactly( + Position.of("b2"), + Position.of("c2"), + Position.of("d2"), + Position.of("e2"), + Position.of("f2") + ); + } +} diff --git a/src/test/java/chess/domain/strategy/move/direction/LeftUpStrategyTest.java b/src/test/java/chess/domain/strategy/move/direction/LeftUpStrategyTest.java new file mode 100644 index 00000000000..8d3582c09c1 --- /dev/null +++ b/src/test/java/chess/domain/strategy/move/direction/LeftUpStrategyTest.java @@ -0,0 +1,26 @@ +package chess.domain.strategy.move.direction; + +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +public class LeftUpStrategyTest { + @DisplayName("좌측 상단 이동 시 경로 구하기") + @Test + void findPathTest() { + DirectionStrategy directionStrategy = new LeftUpStrategy(); + Position source = Position.of("g2"); + Position target = Position.of("b7"); + List path = directionStrategy.findPath(source, target); + + Assertions.assertThat(path).containsExactly( + Position.of("c6"), + Position.of("d5"), + Position.of("e4"), + Position.of("f3") + ); + } +} diff --git a/src/test/java/chess/domain/strategy/move/direction/RightDownStrategyTest.java b/src/test/java/chess/domain/strategy/move/direction/RightDownStrategyTest.java new file mode 100644 index 00000000000..196e8560276 --- /dev/null +++ b/src/test/java/chess/domain/strategy/move/direction/RightDownStrategyTest.java @@ -0,0 +1,26 @@ +package chess.domain.strategy.move.direction; + +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +public class RightDownStrategyTest { + @DisplayName("우측 하단 이동 시 경로 구하기") + @Test + void findPathTest() { + DirectionStrategy directionStrategy = new RightDownStrategy(); + Position source = Position.of("b7"); + Position target = Position.of("g2"); + List path = directionStrategy.findPath(source, target); + + Assertions.assertThat(path).containsExactly( + Position.of("c6"), + Position.of("d5"), + Position.of("e4"), + Position.of("f3") + ); + } +} diff --git a/src/test/java/chess/domain/strategy/move/direction/RightStrategyTest.java b/src/test/java/chess/domain/strategy/move/direction/RightStrategyTest.java new file mode 100644 index 00000000000..0487ca15540 --- /dev/null +++ b/src/test/java/chess/domain/strategy/move/direction/RightStrategyTest.java @@ -0,0 +1,26 @@ +package chess.domain.strategy.move.direction; + +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +public class RightStrategyTest { + @DisplayName("우측 이동 시 경로 구하기") + @Test + void findPathTest() { + DirectionStrategy directionStrategy = new RightStrategy(); + Position source = Position.of("b2"); + Position target = Position.of("g2"); + List path = directionStrategy.findPath(source, target); + + Assertions.assertThat(path).containsExactly( + Position.of("c2"), + Position.of("d2"), + Position.of("e2"), + Position.of("f2") + ); + } +} diff --git a/src/test/java/chess/domain/strategy/move/direction/RightUpStrategyTest.java b/src/test/java/chess/domain/strategy/move/direction/RightUpStrategyTest.java new file mode 100644 index 00000000000..c4903e7303a --- /dev/null +++ b/src/test/java/chess/domain/strategy/move/direction/RightUpStrategyTest.java @@ -0,0 +1,26 @@ +package chess.domain.strategy.move.direction; + +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +public class RightUpStrategyTest { + @DisplayName("우측 상단 이동 시 경로 구하기") + @Test + void findPathTest() { + DirectionStrategy directionStrategy = new RightUpStrategy(); + Position source = Position.of("b2"); + Position target = Position.of("g7"); + List path = directionStrategy.findPath(source, target); + + Assertions.assertThat(path).containsExactly( + Position.of("c3"), + Position.of("d4"), + Position.of("e5"), + Position.of("f6") + ); + } +} diff --git a/src/test/java/chess/domain/strategy/move/direction/UpStrategyTest.java b/src/test/java/chess/domain/strategy/move/direction/UpStrategyTest.java new file mode 100644 index 00000000000..8acb305c8c1 --- /dev/null +++ b/src/test/java/chess/domain/strategy/move/direction/UpStrategyTest.java @@ -0,0 +1,26 @@ +package chess.domain.strategy.move.direction; + +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +public class UpStrategyTest { + @DisplayName("상단 이동 시 경로 구하기") + @Test + void findPathTest() { + DirectionStrategy directionStrategy = new UpStrategy(); + Position source = Position.of("b2"); + Position target = Position.of("b7"); + List path = directionStrategy.findPath(source, target); + + Assertions.assertThat(path).containsExactly( + Position.of("b3"), + Position.of("b4"), + Position.of("b5"), + Position.of("b6") + ); + } +} From 31e70aec16a68c720b9d484135914d18afea8329 Mon Sep 17 00:00:00 2001 From: giantim Date: Tue, 31 Mar 2020 00:46:02 +0900 Subject: [PATCH 23/29] =?UTF-8?q?refactor:=20=EC=BB=A8=ED=8A=B8=EB=A1=A4?= =?UTF-8?q?=EB=9F=AC=20=EC=B6=94=EC=83=81=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chess/controller/ChessController.java | 11 ++++++++ src/main/java/chess/controller/Command.java | 22 +++++++++++----- .../java/chess/controller/EndController.java | 14 +++++++++++ .../java/chess/controller/GameController.java | 25 +++++++++++++++++++ .../java/chess/controller/MoveController.java | 22 ++++++++++++++++ .../chess/controller/StartController.java | 14 +++++++++++ .../chess/controller/StatusController.java | 16 ++++++++++++ 7 files changed, 118 insertions(+), 6 deletions(-) create mode 100644 src/main/java/chess/controller/EndController.java create mode 100644 src/main/java/chess/controller/GameController.java create mode 100644 src/main/java/chess/controller/MoveController.java create mode 100644 src/main/java/chess/controller/StartController.java create mode 100644 src/main/java/chess/controller/StatusController.java diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index 81c2c1da8e5..484f4244bfe 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -29,6 +29,17 @@ public static void start() { } } + public static void run2(ChessRunner chessRunner) { + Command command; + + do { + String commands = inputView.askGameCommand(); + command = Command.of(commands); + GameController gameController = command.getGameController(); + gameController.execute(chessRunner, commands); + } while (!command.isEnd() && findWinner(chessRunner)); + } + private static void run(Command command) { if (command.isStart()) { ChessRunner chessRunner = new ChessRunner(); diff --git a/src/main/java/chess/controller/Command.java b/src/main/java/chess/controller/Command.java index b8585d45382..c140263d451 100644 --- a/src/main/java/chess/controller/Command.java +++ b/src/main/java/chess/controller/Command.java @@ -3,15 +3,17 @@ import java.util.Arrays; public enum Command { - START("start"), - MOVE("move"), - STATUS("status"), - END("end"); + START("start", new StartController()), + MOVE("move", new MoveController()), + STATUS("status", new StatusController()), + END("end", new EndController()); - private String command; + private final String command; + private final GameController gameController; - Command(String command) { + Command(String command, GameController gameController) { this.command = command; + this.gameController = gameController; } public static Command of(final String command) { @@ -24,4 +26,12 @@ public static Command of(final String command) { public boolean isStart() { return this == START; } + + public GameController getGameController() { + return this.gameController; + } + + public boolean isEnd() { + return this == END; + } } diff --git a/src/main/java/chess/controller/EndController.java b/src/main/java/chess/controller/EndController.java new file mode 100644 index 00000000000..5447a5811c3 --- /dev/null +++ b/src/main/java/chess/controller/EndController.java @@ -0,0 +1,14 @@ +package chess.controller; + +import chess.domain.ChessRunner; + +public class EndController extends GameController { + public EndController() { + super(); + } + + @Override + public void execute(ChessRunner chessRunner, String input) { + return; + } +} diff --git a/src/main/java/chess/controller/GameController.java b/src/main/java/chess/controller/GameController.java new file mode 100644 index 00000000000..1bab9902963 --- /dev/null +++ b/src/main/java/chess/controller/GameController.java @@ -0,0 +1,25 @@ +package chess.controller; + +import chess.controller.dto.BoardDto; +import chess.controller.dto.PositionDto; +import chess.domain.ChessRunner; +import chess.domain.board.Board; +import chess.domain.position.Position; +import chess.view.ConsoleOutputView; +import chess.view.OutputView; + +public abstract class GameController { + protected final OutputView outputView; + + public GameController() { + this.outputView = new ConsoleOutputView(); + } + + protected void printBoard(final Board board) { + BoardDto boardDto = new BoardDto(board.parse()); + PositionDto positionDto = new PositionDto(Position.getPositions()); + this.outputView.printBoard(positionDto.getPositions(), boardDto.get()); + } + + public abstract void execute(ChessRunner chessRunner, String input); +} diff --git a/src/main/java/chess/controller/MoveController.java b/src/main/java/chess/controller/MoveController.java new file mode 100644 index 00000000000..6613c3b2e70 --- /dev/null +++ b/src/main/java/chess/controller/MoveController.java @@ -0,0 +1,22 @@ +package chess.controller; + +import chess.domain.ChessRunner; + +public class MoveController extends GameController { + private static final String DELIMITER = " "; + private static final int SOURCE_INDEX = 1; + private static final int TARGET_INDEX = 2; + + public MoveController() { + super(); + } + + @Override + public void execute(ChessRunner chessRunner, String input) { + String[] commands = input.split(DELIMITER); + String source = commands[SOURCE_INDEX]; + String target = commands[TARGET_INDEX]; + chessRunner.update(source, target); + printBoard(chessRunner.getBoard()); + } +} diff --git a/src/main/java/chess/controller/StartController.java b/src/main/java/chess/controller/StartController.java new file mode 100644 index 00000000000..78edcede867 --- /dev/null +++ b/src/main/java/chess/controller/StartController.java @@ -0,0 +1,14 @@ +package chess.controller; + +import chess.domain.ChessRunner; + +public class StartController extends GameController { + public StartController() { + super(); + } + + @Override + public void execute(ChessRunner chessRunner, String input) { + chessRunner = new ChessRunner(); + } +} diff --git a/src/main/java/chess/controller/StatusController.java b/src/main/java/chess/controller/StatusController.java new file mode 100644 index 00000000000..76c3613c5cb --- /dev/null +++ b/src/main/java/chess/controller/StatusController.java @@ -0,0 +1,16 @@ +package chess.controller; + +import chess.domain.ChessRunner; + +public class StatusController extends GameController { + public StatusController() { + super(); + } + + @Override + public void execute(ChessRunner chessRunner, String input) { + double score = chessRunner.calculateScore(); + outputView.printStatus(score, chessRunner.getCurrentTeam()); + printBoard(chessRunner.getBoard()); + } +} From a1f14315d2d643ae97b497a6ca3fe8faf1d4f003 Mon Sep 17 00:00:00 2001 From: giantim Date: Tue, 31 Mar 2020 16:18:59 +0900 Subject: [PATCH 24/29] =?UTF-8?q?refactor:=20=EC=BB=A8=ED=8A=B8=EB=A1=A4?= =?UTF-8?q?=EB=9F=AC=20=EC=B6=94=EC=83=81=ED=99=94(2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chess/controller/ChessController.java | 86 +++---------------- .../chess/controller/StartController.java | 2 +- .../java/chess/view/ConsoleInputView.java | 2 +- 3 files changed, 15 insertions(+), 75 deletions(-) diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index 484f4244bfe..984701bc7a4 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -1,87 +1,40 @@ package chess.controller; -import chess.controller.dto.BoardDto; -import chess.controller.dto.PositionDto; import chess.domain.ChessRunner; -import chess.domain.board.Board; import chess.domain.piece.Team; -import chess.domain.position.Position; import chess.view.ConsoleInputView; import chess.view.ConsoleOutputView; import chess.view.InputView; import chess.view.OutputView; +import org.apache.commons.lang3.StringUtils; public class ChessController { - private static final String DELIMITER = " "; - private static final int SOURCE_INDEX = 1; - private static final int TARGET_INDEX = 2; - private static InputView inputView = new ConsoleInputView(); private static OutputView outputView = new ConsoleOutputView(); public static void start() { try { - Command command = Command.of(inputView.askChessRun()); - run(command); + runChessGame(); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); start(); } } - public static void run2(ChessRunner chessRunner) { - Command command; - - do { - String commands = inputView.askGameCommand(); - command = Command.of(commands); - GameController gameController = command.getGameController(); - gameController.execute(chessRunner, commands); - } while (!command.isEnd() && findWinner(chessRunner)); - } + public static void runChessGame() { + Command command = Command.of(inputView.askChessRun()); - private static void run(Command command) { if (command.isStart()) { ChessRunner chessRunner = new ChessRunner(); - printBoard(chessRunner.getBoard()); - runChess(chessRunner); - } - } - - public static void runChess(ChessRunner chessRunner) { - try { - String input = inputView.askGameCommand(); - Command command = Command.of(input); - - runByCommand(chessRunner, input, command); - } catch (IllegalArgumentException e) { - System.out.println(e.getMessage()); - runChess(chessRunner); - } - } - - private static void runByCommand(ChessRunner chessRunner, String input, Command command) { - switch (command) { - case MOVE: - runMove(chessRunner, input); - break; - case STATUS: - runStatus(chessRunner); - break; - case END: - default: - break; - } - } - - private static void runMove(ChessRunner chessRunner, String input) { - String[] commands = input.split(DELIMITER); - String source = commands[SOURCE_INDEX]; - String target = commands[TARGET_INDEX]; - chessRunner.update(source, target); - printBoard(chessRunner.getBoard()); - if (findWinner(chessRunner)) { - runChess(chessRunner); + GameController startController = command.getGameController(); + startController.execute(chessRunner, StringUtils.EMPTY); + + do { + String commands = inputView.askGameCommand(); + command = Command.of(commands); + GameController gameController = command.getGameController(); + gameController.execute(chessRunner, commands); + } while (!command.isEnd() && findWinner(chessRunner)); } } @@ -93,17 +46,4 @@ private static boolean findWinner(final ChessRunner chessRunner) { } return true; } - - private static void runStatus(ChessRunner chessRunner) { - double score = chessRunner.calculateScore(); - outputView.printStatus(score, chessRunner.getCurrentTeam()); - printBoard(chessRunner.getBoard()); - runChess(chessRunner); - } - - private static void printBoard(final Board board) { - BoardDto boardDto = new BoardDto(board.parse()); - PositionDto positionDto = new PositionDto(Position.getPositions()); - outputView.printBoard(positionDto.getPositions(), boardDto.get()); - } } diff --git a/src/main/java/chess/controller/StartController.java b/src/main/java/chess/controller/StartController.java index 78edcede867..7ce8debfbac 100644 --- a/src/main/java/chess/controller/StartController.java +++ b/src/main/java/chess/controller/StartController.java @@ -9,6 +9,6 @@ public StartController() { @Override public void execute(ChessRunner chessRunner, String input) { - chessRunner = new ChessRunner(); + printBoard(chessRunner.getBoard()); } } diff --git a/src/main/java/chess/view/ConsoleInputView.java b/src/main/java/chess/view/ConsoleInputView.java index caf9c36fe07..0649abe99fb 100644 --- a/src/main/java/chess/view/ConsoleInputView.java +++ b/src/main/java/chess/view/ConsoleInputView.java @@ -11,7 +11,7 @@ public String askChessRun() { System.out.println("> 게임 시작 : start"); System.out.println("> 게임 종료 : end"); System.out.println("> 게임 이동 : move source위치 target위치 - 예. move b2 b3"); - return askGameCommand(); + return SCANNER.nextLine(); } @Override From 7bd04ff7338587c6ff1587566afad39046df58de Mon Sep 17 00:00:00 2001 From: giantim Date: Tue, 31 Mar 2020 22:28:10 +0900 Subject: [PATCH 25/29] =?UTF-8?q?refactor:=201=EC=B0=A8=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 --- .../chess/controller/ChessController.java | 89 +++----------- .../java/chess/controller/MoveController.java | 5 + .../chess/controller/StartController.java | 2 +- .../chess/controller/StatusController.java | 4 +- src/main/java/chess/domain/ChessRunner.java | 64 ++++++++-- src/main/java/chess/domain/board/Board.java | 72 +++++------ .../java/chess/domain/board/BoardScore.java | 26 ++++ src/main/java/chess/domain/piece/Bishop.java | 17 +++ src/main/java/chess/domain/piece/King.java | 21 ++++ src/main/java/chess/domain/piece/Knight.java | 23 ++++ .../java/chess/domain/piece/MoveStrategy.java | 7 ++ src/main/java/chess/domain/piece/Pawn.java | 51 ++++++++ src/main/java/chess/domain/piece/Piece.java | 21 ++-- .../java/chess/domain/piece/PieceType.java | 24 ++-- src/main/java/chess/domain/piece/Queen.java | 15 +++ src/main/java/chess/domain/piece/Rook.java | 22 ++++ src/main/java/chess/domain/piece/Team.java | 4 +- .../{move => }/direction/Direction.java | 2 +- .../direction/DirectionStrategy.java | 2 +- .../{move => }/direction/DownStrategy.java | 3 +- .../direction/LeftDownStrategy.java | 3 +- .../{move => }/direction/LeftStrategy.java | 3 +- .../{move => }/direction/LeftUpStrategy.java | 5 +- .../direction/RightDownStrategy.java | 5 +- .../{move => }/direction/RightStrategy.java | 3 +- .../{move => }/direction/RightUpStrategy.java | 3 +- .../{move => }/direction/UpStrategy.java | 3 +- .../initialize/BishopInitializer.java | 9 +- .../strategy/initialize/KingInitializer.java | 5 +- .../initialize/KnightInitializer.java | 9 +- .../strategy/initialize/PawnInitializer.java | 33 ++--- .../strategy/initialize/QueenInitializer.java | 5 +- .../strategy/initialize/RookInitializer.java | 9 +- .../strategy/move/BishopMoveStrategy.java | 20 ---- .../strategy/move/KingMoveStrategy.java | 19 --- .../strategy/move/KnightMoveStrategy.java | 19 --- .../domain/strategy/move/MoveStrategy.java | 33 ----- .../strategy/move/PawnMoveStrategy.java | 49 -------- .../strategy/move/QueenMoveStrategy.java | 12 -- .../strategy/move/RookMoveStrategy.java | 20 ---- .../java/chess/view/ConsoleInputView.java | 2 +- src/main/java/chess/view/InputView.java | 1 + src/main/java/chess/view/OutputView.java | 2 + .../java/chess/domain/ChessRunnerTest.java | 30 ++++- .../java/chess/domain/board/BoardTest.java | 41 ++++--- .../java/chess/domain/piece/PieceTest.java | 20 ++-- .../java/chess/domain/piece/TeamTest.java | 15 ++- .../{move => }/direction/DirectionTest.java | 2 +- .../direction/DownStrategyTest.java | 2 +- .../direction/LeftDownStrategyTest.java | 2 +- .../direction/LeftStrategyTest.java | 2 +- .../direction/LeftUpStrategyTest.java | 2 +- .../direction/RightDownStrategyTest.java | 2 +- .../direction/RightStrategyTest.java | 2 +- .../direction/RightUpStrategyTest.java | 2 +- .../{move => }/direction/UpStrategyTest.java | 2 +- .../strategy/move/BishopMoveStrategyTest.java | 77 ------------ .../strategy/move/KingMoveStrategyTest.java | 64 ---------- .../strategy/move/KnightMoveStrategyTest.java | 64 ---------- .../strategy/move/PawnMoveStrategyTest.java | 107 ----------------- .../strategy/move/QueenMoveStrategyTest.java | 113 ------------------ .../strategy/move/RookMoveStrategyTest.java | 77 ------------ 62 files changed, 443 insertions(+), 929 deletions(-) create mode 100644 src/main/java/chess/domain/board/BoardScore.java create mode 100644 src/main/java/chess/domain/piece/Bishop.java create mode 100644 src/main/java/chess/domain/piece/King.java create mode 100644 src/main/java/chess/domain/piece/Knight.java create mode 100644 src/main/java/chess/domain/piece/MoveStrategy.java create mode 100644 src/main/java/chess/domain/piece/Pawn.java create mode 100644 src/main/java/chess/domain/piece/Queen.java create mode 100644 src/main/java/chess/domain/piece/Rook.java rename src/main/java/chess/domain/strategy/{move => }/direction/Direction.java (97%) rename src/main/java/chess/domain/strategy/{move => }/direction/DirectionStrategy.java (78%) rename src/main/java/chess/domain/strategy/{move => }/direction/DownStrategy.java (88%) rename src/main/java/chess/domain/strategy/{move => }/direction/LeftDownStrategy.java (89%) rename src/main/java/chess/domain/strategy/{move => }/direction/LeftStrategy.java (88%) rename src/main/java/chess/domain/strategy/{move => }/direction/LeftUpStrategy.java (88%) rename src/main/java/chess/domain/strategy/{move => }/direction/RightDownStrategy.java (85%) rename src/main/java/chess/domain/strategy/{move => }/direction/RightStrategy.java (89%) rename src/main/java/chess/domain/strategy/{move => }/direction/RightUpStrategy.java (89%) rename src/main/java/chess/domain/strategy/{move => }/direction/UpStrategy.java (89%) delete mode 100644 src/main/java/chess/domain/strategy/move/BishopMoveStrategy.java delete mode 100644 src/main/java/chess/domain/strategy/move/KingMoveStrategy.java delete mode 100644 src/main/java/chess/domain/strategy/move/KnightMoveStrategy.java delete mode 100644 src/main/java/chess/domain/strategy/move/MoveStrategy.java delete mode 100644 src/main/java/chess/domain/strategy/move/PawnMoveStrategy.java delete mode 100644 src/main/java/chess/domain/strategy/move/QueenMoveStrategy.java delete mode 100644 src/main/java/chess/domain/strategy/move/RookMoveStrategy.java rename src/test/java/chess/domain/strategy/{move => }/direction/DirectionTest.java (98%) rename src/test/java/chess/domain/strategy/{move => }/direction/DownStrategyTest.java (94%) rename src/test/java/chess/domain/strategy/{move => }/direction/LeftDownStrategyTest.java (94%) rename src/test/java/chess/domain/strategy/{move => }/direction/LeftStrategyTest.java (94%) rename src/test/java/chess/domain/strategy/{move => }/direction/LeftUpStrategyTest.java (94%) rename src/test/java/chess/domain/strategy/{move => }/direction/RightDownStrategyTest.java (94%) rename src/test/java/chess/domain/strategy/{move => }/direction/RightStrategyTest.java (94%) rename src/test/java/chess/domain/strategy/{move => }/direction/RightUpStrategyTest.java (94%) rename src/test/java/chess/domain/strategy/{move => }/direction/UpStrategyTest.java (94%) delete mode 100644 src/test/java/chess/domain/strategy/move/BishopMoveStrategyTest.java delete mode 100644 src/test/java/chess/domain/strategy/move/KingMoveStrategyTest.java delete mode 100644 src/test/java/chess/domain/strategy/move/KnightMoveStrategyTest.java delete mode 100644 src/test/java/chess/domain/strategy/move/PawnMoveStrategyTest.java delete mode 100644 src/test/java/chess/domain/strategy/move/QueenMoveStrategyTest.java delete mode 100644 src/test/java/chess/domain/strategy/move/RookMoveStrategyTest.java diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index 484f4244bfe..0c45cd5ad61 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -1,88 +1,44 @@ package chess.controller; -import chess.controller.dto.BoardDto; -import chess.controller.dto.PositionDto; import chess.domain.ChessRunner; -import chess.domain.board.Board; import chess.domain.piece.Team; -import chess.domain.position.Position; import chess.view.ConsoleInputView; import chess.view.ConsoleOutputView; import chess.view.InputView; import chess.view.OutputView; +import org.apache.commons.lang3.StringUtils; public class ChessController { - private static final String DELIMITER = " "; - private static final int SOURCE_INDEX = 1; - private static final int TARGET_INDEX = 2; - private static InputView inputView = new ConsoleInputView(); private static OutputView outputView = new ConsoleOutputView(); public static void start() { - try { - Command command = Command.of(inputView.askChessRun()); - run(command); - } catch (IllegalArgumentException e) { - System.out.println(e.getMessage()); - start(); + Command command = Command.of(inputView.askChessRun()); + if (command.isStart()) { + ChessRunner chessRunner = new ChessRunner(); + GameController gameController = command.getGameController(); + gameController.execute(chessRunner, StringUtils.EMPTY); + + runChessGame(command, chessRunner); } } - public static void run2(ChessRunner chessRunner) { - Command command; - + private static void runChessGame(Command command, ChessRunner chessRunner) { do { - String commands = inputView.askGameCommand(); - command = Command.of(commands); - GameController gameController = command.getGameController(); - gameController.execute(chessRunner, commands); + command = validateExecute(command, chessRunner); } while (!command.isEnd() && findWinner(chessRunner)); } - private static void run(Command command) { - if (command.isStart()) { - ChessRunner chessRunner = new ChessRunner(); - printBoard(chessRunner.getBoard()); - runChess(chessRunner); - } - } - - public static void runChess(ChessRunner chessRunner) { + private static Command validateExecute(Command command, ChessRunner chessRunner) { try { - String input = inputView.askGameCommand(); - Command command = Command.of(input); - - runByCommand(chessRunner, input, command); + String commands = inputView.askGameCommand(); + command = Command.of(commands); + GameController gameController = command.getGameController(); + gameController.execute(chessRunner, commands); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); - runChess(chessRunner); - } - } - - private static void runByCommand(ChessRunner chessRunner, String input, Command command) { - switch (command) { - case MOVE: - runMove(chessRunner, input); - break; - case STATUS: - runStatus(chessRunner); - break; - case END: - default: - break; - } - } - - private static void runMove(ChessRunner chessRunner, String input) { - String[] commands = input.split(DELIMITER); - String source = commands[SOURCE_INDEX]; - String target = commands[TARGET_INDEX]; - chessRunner.update(source, target); - printBoard(chessRunner.getBoard()); - if (findWinner(chessRunner)) { - runChess(chessRunner); } + return command; } private static boolean findWinner(final ChessRunner chessRunner) { @@ -93,17 +49,4 @@ private static boolean findWinner(final ChessRunner chessRunner) { } return true; } - - private static void runStatus(ChessRunner chessRunner) { - double score = chessRunner.calculateScore(); - outputView.printStatus(score, chessRunner.getCurrentTeam()); - printBoard(chessRunner.getBoard()); - runChess(chessRunner); - } - - private static void printBoard(final Board board) { - BoardDto boardDto = new BoardDto(board.parse()); - PositionDto positionDto = new PositionDto(Position.getPositions()); - outputView.printBoard(positionDto.getPositions(), boardDto.get()); - } } diff --git a/src/main/java/chess/controller/MoveController.java b/src/main/java/chess/controller/MoveController.java index 6613c3b2e70..5c13028fd18 100644 --- a/src/main/java/chess/controller/MoveController.java +++ b/src/main/java/chess/controller/MoveController.java @@ -4,6 +4,7 @@ public class MoveController extends GameController { private static final String DELIMITER = " "; + private static final int COMMANDS_SIZE = 2; private static final int SOURCE_INDEX = 1; private static final int TARGET_INDEX = 2; @@ -14,6 +15,10 @@ public MoveController() { @Override public void execute(ChessRunner chessRunner, String input) { String[] commands = input.split(DELIMITER); + if (commands.length < COMMANDS_SIZE) { + throw new IllegalArgumentException("잘못된 이동 명령어를 입력하였습니다."); + } + String source = commands[SOURCE_INDEX]; String target = commands[TARGET_INDEX]; chessRunner.update(source, target); diff --git a/src/main/java/chess/controller/StartController.java b/src/main/java/chess/controller/StartController.java index 78edcede867..7ce8debfbac 100644 --- a/src/main/java/chess/controller/StartController.java +++ b/src/main/java/chess/controller/StartController.java @@ -9,6 +9,6 @@ public StartController() { @Override public void execute(ChessRunner chessRunner, String input) { - chessRunner = new ChessRunner(); + printBoard(chessRunner.getBoard()); } } diff --git a/src/main/java/chess/controller/StatusController.java b/src/main/java/chess/controller/StatusController.java index 76c3613c5cb..c3443a15bc5 100644 --- a/src/main/java/chess/controller/StatusController.java +++ b/src/main/java/chess/controller/StatusController.java @@ -9,8 +9,8 @@ public StatusController() { @Override public void execute(ChessRunner chessRunner, String input) { - double score = chessRunner.calculateScore(); - outputView.printStatus(score, chessRunner.getCurrentTeam()); +// double score = chessRunner.calculateScore(); +// outputView.printStatus(score, chessRunner.getCurrentTeam()); printBoard(chessRunner.getBoard()); } } diff --git a/src/main/java/chess/domain/ChessRunner.java b/src/main/java/chess/domain/ChessRunner.java index 3a8845d409d..feebf2fdc9c 100644 --- a/src/main/java/chess/domain/ChessRunner.java +++ b/src/main/java/chess/domain/ChessRunner.java @@ -1,9 +1,13 @@ package chess.domain; import chess.domain.board.Board; +import chess.domain.board.BoardScore; import chess.domain.piece.Piece; import chess.domain.piece.Team; import chess.domain.position.Position; +import chess.domain.strategy.direction.Direction; + +import java.util.List; public class ChessRunner { private Board board; @@ -17,17 +21,57 @@ public ChessRunner() { public void update(String source, String target) { Position sourcePosition = Position.of(source); Position targetPosition = Position.of(target); - Piece selectedPiece = this.board.getPiece(sourcePosition); + Piece sourcePiece = this.board.getPiece(sourcePosition); + + checkCorrectTurn(sourcePiece); + checkUpdateBoard(sourcePosition, targetPosition, sourcePiece); + + updateBoard(sourcePosition, targetPosition); + changeTeam(); + } - if (!(currentTeam.isSameTeamWith(selectedPiece.getTeam()))) { + private void checkCorrectTurn(Piece sourcePiece) { + if (sourcePiece.isEnemy(this.currentTeam)) { throw new IllegalArgumentException("현재 차례가 아닙니다."); } + } - if (!(selectedPiece.movable(sourcePosition, targetPosition, board))) { - throw new IllegalArgumentException("이동할 수 없는 곳입니다."); + private void checkUpdateBoard(Position sourcePosition, Position targetPosition, Piece sourcePiece) { + if (isSamePosition(sourcePosition, targetPosition)) { + throw new IllegalArgumentException("같은 위치로 이동할 수 없습니다."); } - updateBoard(sourcePosition, targetPosition); - changeTeam(); + + if (!(sourcePiece.movable(sourcePosition, targetPosition))) { + throw new IllegalArgumentException("선택한 기물이 이동할 수 없는 곳입니다."); + } + + if (!isEmptyPath(sourcePosition, targetPosition)) { + throw new IllegalArgumentException("경로 사이에 장애물이 있습니다."); + } + + if (!movableTarget(sourcePiece, targetPosition)) { + throw new IllegalArgumentException("목적지가 잘못되었습니다."); + } + } + + private boolean isSamePosition(final Position sourcePosition, final Position targetPosition) { + return sourcePosition.equals(targetPosition); + } + + private boolean isEmptyPath(final Position sourcePosition, final Position targetPosition) { + Direction direction = Direction.findDirection(sourcePosition, targetPosition); + List path = direction.findPath(sourcePosition, targetPosition); + + if (path.isEmpty()) { + return true; + } + return path.stream() + .allMatch(this.board::isEmpty); + } + + private boolean movableTarget(final Piece sourcePiece, final Position targetPosition) { + Piece targetPiece = this.board.getPiece(targetPosition); + return sourcePiece.isEnemy(targetPiece); } private void updateBoard(Position sourcePosition, Position targetPosition) { @@ -35,19 +79,19 @@ private void updateBoard(Position sourcePosition, Position targetPosition) { } private void changeTeam() { - this.currentTeam = Team.changeTeam(this.currentTeam); + this.currentTeam = this.currentTeam.changeTeam(); } public Team findWinner() { return this.board.checkWinner(); } - public double calculateScore() { - return board.calculateScore(currentTeam); + public BoardScore calculateScore() { + return board.calculateScore(this.currentTeam); } public Team getCurrentTeam() { - return currentTeam; + return this.currentTeam; } public Board getBoard() { diff --git a/src/main/java/chess/domain/board/Board.java b/src/main/java/chess/domain/board/Board.java index d42f958b544..53188c00728 100644 --- a/src/main/java/chess/domain/board/Board.java +++ b/src/main/java/chess/domain/board/Board.java @@ -12,9 +12,6 @@ import java.util.stream.Collectors; public class Board { - private static final int PAWN_ON_SAME_FILE = 1; - private static final double PAWN_SCORE_STRATEGY = 0.5; - private final Map board; public Board() { @@ -25,22 +22,37 @@ public Board(final Map board) { this.board = board; } - public Map parse() { - Map parseResult = board.entrySet() - .stream() - .collect(Collectors.toMap(entry -> entry.getKey().toString(), - entry -> entry.getValue().toSymbol(), - (e1, e2) -> e1, LinkedHashMap::new)); - - return Collections.unmodifiableMap(parseResult); - } - public void updateBoard(final Position sourcePosition, final Position targetPosition) { Piece selectedPiece = this.board.get(sourcePosition); this.board.put(targetPosition, selectedPiece); this.board.remove(sourcePosition); } + public BoardScore calculateScore(final Team team) { + BoardScore totalScore = calculateTotalScore(team); + return calculatePawnScore(team, totalScore); + } + + private BoardScore calculateTotalScore(final Team team) { + double totalScore = board.values().stream() + .filter(piece -> team.isSameTeamWith(piece.getTeam())) + .mapToDouble(Piece::getScore) + .sum(); + return new BoardScore(totalScore); + } + + private BoardScore calculatePawnScore(final Team team, BoardScore totalScore) { + for (File file : File.values()) { + List> sameFilePawns = this.board.entrySet().stream() + .filter(entry -> File.of(entry.getKey().getFile()).equals(file)) + .filter(entry -> entry.getValue().isPawn() && !entry.getValue().isEnemy(team)) + .collect(Collectors.toList()); + + totalScore = totalScore.pawnStrategy(sameFilePawns); + } + return totalScore; + } + public Team checkWinner() { if (checkWhiteKing() && !checkBlackKing()) { return Team.WHITE; @@ -66,32 +78,20 @@ public boolean isEmpty(final Position position) { } public Piece getPiece(final Position position) { - return this.board.get(position); - } - - public double calculateScore(final Team team) { - double totalScore = calculateTotalScore(team); - return calculatePawnScore(team, totalScore); - } + if (!this.board.containsKey(position)) { + throw new IllegalArgumentException("비어있는 위치를 선택하였습니다."); + } - private double calculateTotalScore(final Team team) { - return board.values().stream() - .filter(piece -> team.isSameTeamWith(piece.getTeam())) - .mapToDouble(Piece::getScore) - .sum(); + return this.board.get(position); } - private double calculatePawnScore(final Team team, double score) { - for (File file : File.values()) { - List> sameFile = this.board.entrySet().stream() - .filter(entry -> File.of(entry.getKey().getFile()).equals(file)) - .filter(entry -> entry.getValue().isPawn() && !entry.getValue().isEnemy(team)) - .collect(Collectors.toList()); + public Map parse() { + Map parseResult = board.entrySet() + .stream() + .collect(Collectors.toMap(entry -> entry.getKey().toString(), + entry -> entry.getValue().toSymbol(), + (e1, e2) -> e1, LinkedHashMap::new)); - if (sameFile.size() > PAWN_ON_SAME_FILE) { - score -= sameFile.size() * PAWN_SCORE_STRATEGY; - } - } - return score; + return Collections.unmodifiableMap(parseResult); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/board/BoardScore.java b/src/main/java/chess/domain/board/BoardScore.java new file mode 100644 index 00000000000..9525bd8ec69 --- /dev/null +++ b/src/main/java/chess/domain/board/BoardScore.java @@ -0,0 +1,26 @@ +package chess.domain.board; + +import chess.domain.piece.Piece; +import chess.domain.position.Position; + +import java.util.List; +import java.util.Map; + +public class BoardScore { + private static final int PAWN_ON_SAME_FILE = 1; + private static final double PAWN_SCORE_STRATEGY = 0.5; + + private final double boardScore; + + public BoardScore(final double boardScore) { + this.boardScore = boardScore; + } + + public BoardScore pawnStrategy(List> sameFilePawns) { + int pawnsCount = sameFilePawns.size(); + if (pawnsCount > PAWN_ON_SAME_FILE) { + return new BoardScore(this.boardScore - (pawnsCount * PAWN_SCORE_STRATEGY)); + } + return this; + } +} diff --git a/src/main/java/chess/domain/piece/Bishop.java b/src/main/java/chess/domain/piece/Bishop.java new file mode 100644 index 00000000000..7151af78465 --- /dev/null +++ b/src/main/java/chess/domain/piece/Bishop.java @@ -0,0 +1,17 @@ +package chess.domain.piece; + +import chess.domain.position.Position; + +public class Bishop extends Piece { + public Bishop(PieceType pieceType, Team team) { + super(pieceType, team); + } + + @Override + public boolean movable(Position source, Position target) { + int fileGap = Math.abs(source.calculateFileGap(target)); + int rankGap = Math.abs(source.calculateRankGap(target)); + + return fileGap == rankGap; + } +} diff --git a/src/main/java/chess/domain/piece/King.java b/src/main/java/chess/domain/piece/King.java new file mode 100644 index 00000000000..d671b45b632 --- /dev/null +++ b/src/main/java/chess/domain/piece/King.java @@ -0,0 +1,21 @@ +package chess.domain.piece; + +import chess.domain.position.Position; + +public class King extends Piece { + private static final int MAX_FILE_GAP = 1; + private static final int MAX_RANK_GAP = 1; + + public King(PieceType pieceType, Team team) { + super(pieceType, team); + } + + @Override + public boolean movable(Position source, Position target) { + int fileGap = Math.abs(source.calculateFileGap(target)); + int rankGap = Math.abs(source.calculateRankGap(target)); + + return fileGap <= MAX_FILE_GAP + && rankGap <= MAX_RANK_GAP; + } +} diff --git a/src/main/java/chess/domain/piece/Knight.java b/src/main/java/chess/domain/piece/Knight.java new file mode 100644 index 00000000000..c7908365708 --- /dev/null +++ b/src/main/java/chess/domain/piece/Knight.java @@ -0,0 +1,23 @@ +package chess.domain.piece; + +import chess.domain.position.Position; + +public class Knight extends Piece { + private static final int HORIZONTAL_FILE_GAP = 2; + private static final int HORIZONTAL_RANK_GAP = 1; + private static final int VERTICAL_FILE_GAP = 1; + private static final int VERTICAL_RANK_GAP = 2; + + public Knight(PieceType pieceType, Team team) { + super(pieceType, team); + } + + @Override + public boolean movable(Position source, Position target) { + int fileGap = Math.abs(source.calculateFileGap(target)); + int rankGap = Math.abs(source.calculateRankGap(target)); + + return (fileGap == HORIZONTAL_FILE_GAP && rankGap == HORIZONTAL_RANK_GAP) + || (fileGap == VERTICAL_FILE_GAP && rankGap == VERTICAL_RANK_GAP); + } +} diff --git a/src/main/java/chess/domain/piece/MoveStrategy.java b/src/main/java/chess/domain/piece/MoveStrategy.java new file mode 100644 index 00000000000..75726bc7ee6 --- /dev/null +++ b/src/main/java/chess/domain/piece/MoveStrategy.java @@ -0,0 +1,7 @@ +package chess.domain.piece; + +import chess.domain.position.Position; + +public interface MoveStrategy { + boolean movable(Position source, Position target); +} diff --git a/src/main/java/chess/domain/piece/Pawn.java b/src/main/java/chess/domain/piece/Pawn.java new file mode 100644 index 00000000000..6d34deb7351 --- /dev/null +++ b/src/main/java/chess/domain/piece/Pawn.java @@ -0,0 +1,51 @@ +package chess.domain.piece; + +import chess.domain.position.Position; + +public class Pawn extends Piece { + private static final int START_WHITE_RANK = 2; + private static final int START_BLACK_RANK = 7; + private static final int SAME_FILE = 0; + private static final int DIAGONAL = 1; + private static final int UP_WHITE_ONE = -1; + private static final int UP_WHITE_TWO = -2; + private static final int DOWN_BLACK_ONE = 1; + private static final int DOWN_BLACK_TWO = 2; + + public Pawn(final PieceType pieceType, final Team team) { + super(pieceType, team); + } + + @Override + public boolean movable(final Position source, final Position target) { + final int fileGap = source.calculateFileGap(target); + final int rankGap = source.calculateRankGap(target); + + if (this.team.isWhite()) { + return whitePawnMovable(source, fileGap, rankGap); + } + return blackPawnMovable(source, fileGap, rankGap); + } + + private boolean whitePawnMovable(final Position source, final int fileGap, final int rankGap) { + if (source.getRank() == START_WHITE_RANK) { + return fileGap == SAME_FILE + && (rankGap == UP_WHITE_ONE || rankGap == UP_WHITE_TWO); + } + + final int absFileGap = Math.abs(fileGap); + return (absFileGap == SAME_FILE || absFileGap == DIAGONAL) + && rankGap == UP_WHITE_ONE; + } + + private boolean blackPawnMovable(final Position source, final int fileGap, final int rankGap) { + if (source.getRank() == START_BLACK_RANK) { + return fileGap == SAME_FILE + && (rankGap == DOWN_BLACK_ONE || rankGap == DOWN_BLACK_TWO); + } + + final int absFileGap = Math.abs(fileGap); + return (absFileGap == SAME_FILE || absFileGap == DIAGONAL) + && rankGap == DOWN_BLACK_ONE; + } +} diff --git a/src/main/java/chess/domain/piece/Piece.java b/src/main/java/chess/domain/piece/Piece.java index 5169eb6c99c..a09e9aacb87 100644 --- a/src/main/java/chess/domain/piece/Piece.java +++ b/src/main/java/chess/domain/piece/Piece.java @@ -1,25 +1,14 @@ package chess.domain.piece; -import chess.domain.board.Board; -import chess.domain.position.Position; - -public class Piece { - private final PieceType pieceType; - private final Team team; +public abstract class Piece implements MoveStrategy { + protected final PieceType pieceType; + protected final Team team; public Piece(final PieceType pieceType, final Team team) { this.pieceType = pieceType; this.team = team; } - public String toSymbol() { - return this.team.symbolize(this.pieceType.getSymbol()); - } - - public boolean movable(final Position source, final Position target, final Board board) { - return this.pieceType.movable(source, target, board); - } - public boolean isEnemy(final Piece targetPiece) { return !this.team.isSameTeamWith(targetPiece.getTeam()); } @@ -40,6 +29,10 @@ public boolean isPawn() { return this.pieceType.isPawn(); } + public String toSymbol() { + return this.team.symbolize(this.pieceType.getSymbol()); + } + public Team getTeam() { return this.team; } diff --git a/src/main/java/chess/domain/piece/PieceType.java b/src/main/java/chess/domain/piece/PieceType.java index f50f5efc873..6640ffa3d86 100644 --- a/src/main/java/chess/domain/piece/PieceType.java +++ b/src/main/java/chess/domain/piece/PieceType.java @@ -1,29 +1,19 @@ package chess.domain.piece; -import chess.domain.board.Board; -import chess.domain.position.Position; -import chess.domain.strategy.move.*; - public enum PieceType { - KING("k", 0, new KingMoveStrategy()), - QUEEN("q", 9, new QueenMoveStrategy()), - ROOK("r", 5, new RookMoveStrategy()), - BISHOP("b", 3, new BishopMoveStrategy()), - KNIGHT("n", 2.5, new KnightMoveStrategy()), - PAWN("p", 1, new PawnMoveStrategy()); + KING("k", 0), + QUEEN("q", 9), + ROOK("r", 5), + BISHOP("b", 3), + KNIGHT("n", 2.5), + PAWN("p", 1); private final String symbol; private final double score; - private final MoveStrategy moveStrategy; - PieceType(String symbol, double score, MoveStrategy moveStrategy) { + PieceType(String symbol, double score) { this.symbol = symbol; this.score = score; - this.moveStrategy = moveStrategy; - } - - public boolean movable(final Position source, final Position target, final Board board) { - return this.moveStrategy.movable(source, target, board); } public boolean isKing() { diff --git a/src/main/java/chess/domain/piece/Queen.java b/src/main/java/chess/domain/piece/Queen.java new file mode 100644 index 00000000000..c7379c01f75 --- /dev/null +++ b/src/main/java/chess/domain/piece/Queen.java @@ -0,0 +1,15 @@ +package chess.domain.piece; + +import chess.domain.position.Position; + +public class Queen extends Piece { + public Queen(PieceType pieceType, Team team) { + super(pieceType, team); + } + + @Override + public boolean movable(Position source, Position target) { + return new Rook(this.pieceType, this.team).movable(source, target) + && new Bishop(this.pieceType, this.team).movable(source, target); + } +} diff --git a/src/main/java/chess/domain/piece/Rook.java b/src/main/java/chess/domain/piece/Rook.java new file mode 100644 index 00000000000..791c12d4c66 --- /dev/null +++ b/src/main/java/chess/domain/piece/Rook.java @@ -0,0 +1,22 @@ +package chess.domain.piece; + +import chess.domain.position.Position; + +public class Rook extends Piece { + + private static final int MIN_FILE_GAP = 0; + private static final int MIN_RANK_GAP = 0; + + public Rook(PieceType pieceType, Team team) { + super(pieceType, team); + } + + @Override + public boolean movable(Position source, Position target) { + int fileGap = Math.abs(source.calculateFileGap(target)); + int rankGap = Math.abs(source.calculateRankGap(target)); + + return (fileGap > MIN_FILE_GAP && rankGap == MIN_RANK_GAP) + || (fileGap == MIN_FILE_GAP && rankGap > MIN_RANK_GAP); + } +} diff --git a/src/main/java/chess/domain/piece/Team.java b/src/main/java/chess/domain/piece/Team.java index 6ae03e8124d..593352c6ab2 100644 --- a/src/main/java/chess/domain/piece/Team.java +++ b/src/main/java/chess/domain/piece/Team.java @@ -12,8 +12,8 @@ public enum Team { this.expression = expression; } - public static Team changeTeam(final Team team) { - if (team == BLACK) { + public Team changeTeam() { + if (this == BLACK) { return WHITE; } return BLACK; diff --git a/src/main/java/chess/domain/strategy/move/direction/Direction.java b/src/main/java/chess/domain/strategy/direction/Direction.java similarity index 97% rename from src/main/java/chess/domain/strategy/move/direction/Direction.java rename to src/main/java/chess/domain/strategy/direction/Direction.java index 857ad66d9a7..50aa5d53255 100644 --- a/src/main/java/chess/domain/strategy/move/direction/Direction.java +++ b/src/main/java/chess/domain/strategy/direction/Direction.java @@ -1,4 +1,4 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/strategy/move/direction/DirectionStrategy.java b/src/main/java/chess/domain/strategy/direction/DirectionStrategy.java similarity index 78% rename from src/main/java/chess/domain/strategy/move/direction/DirectionStrategy.java rename to src/main/java/chess/domain/strategy/direction/DirectionStrategy.java index d9d3f558288..ec27cd66a4a 100644 --- a/src/main/java/chess/domain/strategy/move/direction/DirectionStrategy.java +++ b/src/main/java/chess/domain/strategy/direction/DirectionStrategy.java @@ -1,4 +1,4 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; diff --git a/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java b/src/main/java/chess/domain/strategy/direction/DownStrategy.java similarity index 88% rename from src/main/java/chess/domain/strategy/move/direction/DownStrategy.java rename to src/main/java/chess/domain/strategy/direction/DownStrategy.java index 9d0cae3a260..4c934153ce7 100644 --- a/src/main/java/chess/domain/strategy/move/direction/DownStrategy.java +++ b/src/main/java/chess/domain/strategy/direction/DownStrategy.java @@ -1,8 +1,7 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; diff --git a/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java b/src/main/java/chess/domain/strategy/direction/LeftDownStrategy.java similarity index 89% rename from src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java rename to src/main/java/chess/domain/strategy/direction/LeftDownStrategy.java index 0b2927ebcfb..9eb5797914a 100644 --- a/src/main/java/chess/domain/strategy/move/direction/LeftDownStrategy.java +++ b/src/main/java/chess/domain/strategy/direction/LeftDownStrategy.java @@ -1,8 +1,7 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; diff --git a/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java b/src/main/java/chess/domain/strategy/direction/LeftStrategy.java similarity index 88% rename from src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java rename to src/main/java/chess/domain/strategy/direction/LeftStrategy.java index e95cbff9e82..9c03bab43ba 100644 --- a/src/main/java/chess/domain/strategy/move/direction/LeftStrategy.java +++ b/src/main/java/chess/domain/strategy/direction/LeftStrategy.java @@ -1,8 +1,7 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; diff --git a/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java b/src/main/java/chess/domain/strategy/direction/LeftUpStrategy.java similarity index 88% rename from src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java rename to src/main/java/chess/domain/strategy/direction/LeftUpStrategy.java index 03400dc3e29..7be9d112170 100644 --- a/src/main/java/chess/domain/strategy/move/direction/LeftUpStrategy.java +++ b/src/main/java/chess/domain/strategy/direction/LeftUpStrategy.java @@ -1,8 +1,7 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -14,7 +13,7 @@ public List findPath(final Position source, final Position target) { List path = IntStream.range(target.getFile() + 1, source.getFile()) .mapToObj(index -> Position.of(index, target.getRank() + (target.getFile() - index))) .collect(Collectors.toList()); - + return Collections.unmodifiableList(path); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java b/src/main/java/chess/domain/strategy/direction/RightDownStrategy.java similarity index 85% rename from src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java rename to src/main/java/chess/domain/strategy/direction/RightDownStrategy.java index 9a304efcfaa..6f8988b2d0c 100644 --- a/src/main/java/chess/domain/strategy/move/direction/RightDownStrategy.java +++ b/src/main/java/chess/domain/strategy/direction/RightDownStrategy.java @@ -1,8 +1,7 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -12,7 +11,7 @@ public final class RightDownStrategy implements DirectionStrategy { @Override public List findPath(final Position source, final Position target) { - List path = IntStream.rangeClosed(source.getFile() + 1, target.getFile() -1) + List path = IntStream.rangeClosed(source.getFile() + 1, target.getFile() - 1) .mapToObj(index -> Position.of(index, target.getRank() + (target.getFile() - index))) .collect(Collectors.toList()); diff --git a/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java b/src/main/java/chess/domain/strategy/direction/RightStrategy.java similarity index 89% rename from src/main/java/chess/domain/strategy/move/direction/RightStrategy.java rename to src/main/java/chess/domain/strategy/direction/RightStrategy.java index 112de22e38f..f665648ee0a 100644 --- a/src/main/java/chess/domain/strategy/move/direction/RightStrategy.java +++ b/src/main/java/chess/domain/strategy/direction/RightStrategy.java @@ -1,8 +1,7 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; diff --git a/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java b/src/main/java/chess/domain/strategy/direction/RightUpStrategy.java similarity index 89% rename from src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java rename to src/main/java/chess/domain/strategy/direction/RightUpStrategy.java index ffadef2983d..f321d432ef1 100644 --- a/src/main/java/chess/domain/strategy/move/direction/RightUpStrategy.java +++ b/src/main/java/chess/domain/strategy/direction/RightUpStrategy.java @@ -1,8 +1,7 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; diff --git a/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java b/src/main/java/chess/domain/strategy/direction/UpStrategy.java similarity index 89% rename from src/main/java/chess/domain/strategy/move/direction/UpStrategy.java rename to src/main/java/chess/domain/strategy/direction/UpStrategy.java index 8c7e704a4a8..c309ae1f086 100644 --- a/src/main/java/chess/domain/strategy/move/direction/UpStrategy.java +++ b/src/main/java/chess/domain/strategy/direction/UpStrategy.java @@ -1,8 +1,7 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; diff --git a/src/main/java/chess/domain/strategy/initialize/BishopInitializer.java b/src/main/java/chess/domain/strategy/initialize/BishopInitializer.java index aa96685bbe1..59fdbc8d981 100644 --- a/src/main/java/chess/domain/strategy/initialize/BishopInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/BishopInitializer.java @@ -1,5 +1,6 @@ package chess.domain.strategy.initialize; +import chess.domain.piece.Bishop; import chess.domain.piece.Piece; import chess.domain.piece.PieceType; import chess.domain.piece.Team; @@ -13,10 +14,10 @@ public final class BishopInitializer implements InitializeStrategy { @Override public Map initialize() { Map pieces = new HashMap<>(); - pieces.put(Position.of("c8"), new Piece(PieceType.BISHOP, Team.BLACK)); - pieces.put(Position.of("c1"), new Piece(PieceType.BISHOP, Team.WHITE)); - pieces.put(Position.of("f8"), new Piece(PieceType.BISHOP, Team.BLACK)); - pieces.put(Position.of("f1"), new Piece(PieceType.BISHOP, Team.WHITE)); + pieces.put(Position.of("c8"), new Bishop(PieceType.BISHOP, Team.BLACK)); + pieces.put(Position.of("c1"), new Bishop(PieceType.BISHOP, Team.WHITE)); + pieces.put(Position.of("f8"), new Bishop(PieceType.BISHOP, Team.BLACK)); + pieces.put(Position.of("f1"), new Bishop(PieceType.BISHOP, Team.WHITE)); return Collections.unmodifiableMap(pieces); } diff --git a/src/main/java/chess/domain/strategy/initialize/KingInitializer.java b/src/main/java/chess/domain/strategy/initialize/KingInitializer.java index 31346c488f2..598495e1f75 100644 --- a/src/main/java/chess/domain/strategy/initialize/KingInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/KingInitializer.java @@ -1,5 +1,6 @@ package chess.domain.strategy.initialize; +import chess.domain.piece.King; import chess.domain.piece.Piece; import chess.domain.piece.PieceType; import chess.domain.piece.Team; @@ -13,8 +14,8 @@ public final class KingInitializer implements InitializeStrategy { @Override public Map initialize() { Map pieces = new HashMap<>(); - pieces.put(Position.of("e8"), new Piece(PieceType.KING, Team.BLACK)); - pieces.put(Position.of("e1"), new Piece(PieceType.KING, Team.WHITE)); + pieces.put(Position.of("e8"), new King(PieceType.KING, Team.BLACK)); + pieces.put(Position.of("e1"), new King(PieceType.KING, Team.WHITE)); return Collections.unmodifiableMap(pieces); } diff --git a/src/main/java/chess/domain/strategy/initialize/KnightInitializer.java b/src/main/java/chess/domain/strategy/initialize/KnightInitializer.java index 610e7e8864c..d2863dde2e1 100644 --- a/src/main/java/chess/domain/strategy/initialize/KnightInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/KnightInitializer.java @@ -1,5 +1,6 @@ package chess.domain.strategy.initialize; +import chess.domain.piece.Knight; import chess.domain.piece.Piece; import chess.domain.piece.PieceType; import chess.domain.piece.Team; @@ -13,10 +14,10 @@ public final class KnightInitializer implements InitializeStrategy { @Override public Map initialize() { Map pieces = new HashMap<>(); - pieces.put(Position.of("b8"), new Piece(PieceType.KNIGHT, Team.BLACK)); - pieces.put(Position.of("b1"), new Piece(PieceType.KNIGHT, Team.WHITE)); - pieces.put(Position.of("g8"), new Piece(PieceType.KNIGHT, Team.BLACK)); - pieces.put(Position.of("g1"), new Piece(PieceType.KNIGHT, Team.WHITE)); + pieces.put(Position.of("b8"), new Knight(PieceType.KNIGHT, Team.BLACK)); + pieces.put(Position.of("b1"), new Knight(PieceType.KNIGHT, Team.WHITE)); + pieces.put(Position.of("g8"), new Knight(PieceType.KNIGHT, Team.BLACK)); + pieces.put(Position.of("g1"), new Knight(PieceType.KNIGHT, Team.WHITE)); return Collections.unmodifiableMap(pieces); } diff --git a/src/main/java/chess/domain/strategy/initialize/PawnInitializer.java b/src/main/java/chess/domain/strategy/initialize/PawnInitializer.java index fae533df5d9..e9296b8bc57 100644 --- a/src/main/java/chess/domain/strategy/initialize/PawnInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/PawnInitializer.java @@ -1,5 +1,6 @@ package chess.domain.strategy.initialize; +import chess.domain.piece.Pawn; import chess.domain.piece.Piece; import chess.domain.piece.PieceType; import chess.domain.piece.Team; @@ -13,23 +14,23 @@ public final class PawnInitializer implements InitializeStrategy { @Override public Map initialize() { Map pieces = new HashMap<>(); - pieces.put(Position.of("a7"), new Piece(PieceType.PAWN, Team.BLACK)); - pieces.put(Position.of("b7"), new Piece(PieceType.PAWN, Team.BLACK)); - pieces.put(Position.of("c7"), new Piece(PieceType.PAWN, Team.BLACK)); - pieces.put(Position.of("d7"), new Piece(PieceType.PAWN, Team.BLACK)); - pieces.put(Position.of("e7"), new Piece(PieceType.PAWN, Team.BLACK)); - pieces.put(Position.of("f7"), new Piece(PieceType.PAWN, Team.BLACK)); - pieces.put(Position.of("g7"), new Piece(PieceType.PAWN, Team.BLACK)); - pieces.put(Position.of("h7"), new Piece(PieceType.PAWN, Team.BLACK)); + pieces.put(Position.of("a7"), new Pawn(PieceType.PAWN, Team.BLACK)); + pieces.put(Position.of("b7"), new Pawn(PieceType.PAWN, Team.BLACK)); + pieces.put(Position.of("c7"), new Pawn(PieceType.PAWN, Team.BLACK)); + pieces.put(Position.of("d7"), new Pawn(PieceType.PAWN, Team.BLACK)); + pieces.put(Position.of("e7"), new Pawn(PieceType.PAWN, Team.BLACK)); + pieces.put(Position.of("f7"), new Pawn(PieceType.PAWN, Team.BLACK)); + pieces.put(Position.of("g7"), new Pawn(PieceType.PAWN, Team.BLACK)); + pieces.put(Position.of("h7"), new Pawn(PieceType.PAWN, Team.BLACK)); - pieces.put(Position.of("a2"), new Piece(PieceType.PAWN, Team.WHITE)); - pieces.put(Position.of("b2"), new Piece(PieceType.PAWN, Team.WHITE)); - pieces.put(Position.of("c2"), new Piece(PieceType.PAWN, Team.WHITE)); - pieces.put(Position.of("d2"), new Piece(PieceType.PAWN, Team.WHITE)); - pieces.put(Position.of("e2"), new Piece(PieceType.PAWN, Team.WHITE)); - pieces.put(Position.of("f2"), new Piece(PieceType.PAWN, Team.WHITE)); - pieces.put(Position.of("g2"), new Piece(PieceType.PAWN, Team.WHITE)); - pieces.put(Position.of("h2"), new Piece(PieceType.PAWN, Team.WHITE)); + pieces.put(Position.of("a2"), new Pawn(PieceType.PAWN, Team.WHITE)); + pieces.put(Position.of("b2"), new Pawn(PieceType.PAWN, Team.WHITE)); + pieces.put(Position.of("c2"), new Pawn(PieceType.PAWN, Team.WHITE)); + pieces.put(Position.of("d2"), new Pawn(PieceType.PAWN, Team.WHITE)); + pieces.put(Position.of("e2"), new Pawn(PieceType.PAWN, Team.WHITE)); + pieces.put(Position.of("f2"), new Pawn(PieceType.PAWN, Team.WHITE)); + pieces.put(Position.of("g2"), new Pawn(PieceType.PAWN, Team.WHITE)); + pieces.put(Position.of("h2"), new Pawn(PieceType.PAWN, Team.WHITE)); return Collections.unmodifiableMap(pieces); } diff --git a/src/main/java/chess/domain/strategy/initialize/QueenInitializer.java b/src/main/java/chess/domain/strategy/initialize/QueenInitializer.java index d13feded160..64ea4cfc49d 100644 --- a/src/main/java/chess/domain/strategy/initialize/QueenInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/QueenInitializer.java @@ -2,6 +2,7 @@ import chess.domain.piece.Piece; import chess.domain.piece.PieceType; +import chess.domain.piece.Queen; import chess.domain.piece.Team; import chess.domain.position.Position; @@ -13,8 +14,8 @@ public final class QueenInitializer implements InitializeStrategy { @Override public Map initialize() { Map pieces = new HashMap<>(); - pieces.put(Position.of("d8"), new Piece(PieceType.QUEEN, Team.BLACK)); - pieces.put(Position.of("d1"), new Piece(PieceType.QUEEN, Team.WHITE)); + pieces.put(Position.of("d8"), new Queen(PieceType.QUEEN, Team.BLACK)); + pieces.put(Position.of("d1"), new Queen(PieceType.QUEEN, Team.WHITE)); return Collections.unmodifiableMap(pieces); } diff --git a/src/main/java/chess/domain/strategy/initialize/RookInitializer.java b/src/main/java/chess/domain/strategy/initialize/RookInitializer.java index c1409b0f6c0..efcfbe69b8f 100644 --- a/src/main/java/chess/domain/strategy/initialize/RookInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/RookInitializer.java @@ -2,6 +2,7 @@ import chess.domain.piece.Piece; import chess.domain.piece.PieceType; +import chess.domain.piece.Rook; import chess.domain.piece.Team; import chess.domain.position.Position; @@ -13,10 +14,10 @@ public final class RookInitializer implements InitializeStrategy { @Override public Map initialize() { Map pieces = new HashMap<>(); - pieces.put(Position.of("a8"), new Piece(PieceType.ROOK, Team.BLACK)); - pieces.put(Position.of("a1"), new Piece(PieceType.ROOK, Team.WHITE)); - pieces.put(Position.of("h8"), new Piece(PieceType.ROOK, Team.BLACK)); - pieces.put(Position.of("h1"), new Piece(PieceType.ROOK, Team.WHITE)); + pieces.put(Position.of("a8"), new Rook(PieceType.ROOK, Team.BLACK)); + pieces.put(Position.of("a1"), new Rook(PieceType.ROOK, Team.WHITE)); + pieces.put(Position.of("h8"), new Rook(PieceType.ROOK, Team.BLACK)); + pieces.put(Position.of("h1"), new Rook(PieceType.ROOK, Team.WHITE)); return Collections.unmodifiableMap(pieces); } diff --git a/src/main/java/chess/domain/strategy/move/BishopMoveStrategy.java b/src/main/java/chess/domain/strategy/move/BishopMoveStrategy.java deleted file mode 100644 index 2d6b99cda57..00000000000 --- a/src/main/java/chess/domain/strategy/move/BishopMoveStrategy.java +++ /dev/null @@ -1,20 +0,0 @@ -package chess.domain.strategy.move; - -import chess.domain.board.Board; -import chess.domain.position.Position; - -public final class BishopMoveStrategy extends MoveStrategy { - @Override - public boolean movable(final Position source, final Position target, final Board board) { - if (isSamePosition(source, target)) { - return false; - } - - int fileGap = Math.abs(source.calculateFileGap(target)); - int rankGap = Math.abs(source.calculateRankGap(target)); - - return (fileGap == rankGap) - && checkObstacle(source, target, board) - && checkTarget(source, target, board); - } -} diff --git a/src/main/java/chess/domain/strategy/move/KingMoveStrategy.java b/src/main/java/chess/domain/strategy/move/KingMoveStrategy.java deleted file mode 100644 index 1b7c157e9e1..00000000000 --- a/src/main/java/chess/domain/strategy/move/KingMoveStrategy.java +++ /dev/null @@ -1,19 +0,0 @@ -package chess.domain.strategy.move; - -import chess.domain.board.Board; -import chess.domain.position.Position; - -public final class KingMoveStrategy extends MoveStrategy { - @Override - public boolean movable(final Position source, final Position target, final Board board) { - if (isSamePosition(source, target)) { - return false; - } - - int fileGap = Math.abs(source.calculateFileGap(target)); - int rankGap = Math.abs(source.calculateRankGap(target)); - - return (fileGap <= 1 && rankGap <= 1) - && checkTarget(source, target, board); - } -} diff --git a/src/main/java/chess/domain/strategy/move/KnightMoveStrategy.java b/src/main/java/chess/domain/strategy/move/KnightMoveStrategy.java deleted file mode 100644 index 7a2e2676256..00000000000 --- a/src/main/java/chess/domain/strategy/move/KnightMoveStrategy.java +++ /dev/null @@ -1,19 +0,0 @@ -package chess.domain.strategy.move; - -import chess.domain.board.Board; -import chess.domain.position.Position; - -public final class KnightMoveStrategy extends MoveStrategy { - @Override - public boolean movable(final Position source, final Position target, final Board board) { - if (isSamePosition(source, target)) { - return false; - } - - int fileGap = Math.abs(source.calculateFileGap(target)); - int rankGap = Math.abs(source.calculateRankGap(target)); - - return (fileGap == 2 && rankGap == 1) || (fileGap == 1 && rankGap == 2) - && checkTarget(source, target, board); - } -} \ No newline at end of file diff --git a/src/main/java/chess/domain/strategy/move/MoveStrategy.java b/src/main/java/chess/domain/strategy/move/MoveStrategy.java deleted file mode 100644 index 5b6395ce053..00000000000 --- a/src/main/java/chess/domain/strategy/move/MoveStrategy.java +++ /dev/null @@ -1,33 +0,0 @@ -package chess.domain.strategy.move; - -import chess.domain.board.Board; -import chess.domain.piece.Piece; -import chess.domain.position.Position; -import chess.domain.strategy.move.direction.Direction; - -import java.util.List; - -public abstract class MoveStrategy { - protected boolean isSamePosition(final Position source, final Position target) { - return source.equals(target); - } - - protected boolean checkObstacle(final Position source, final Position target, final Board board) { - Direction direction = Direction.findDirection(source, target); - List path = direction.findPath(source, target); - - return path.stream() - .allMatch(board::isEmpty); - } - - protected boolean checkTarget(final Position source, final Position target, final Board board) { - Piece sourcePiece = board.getPiece(source); - if (board.isEmpty(target)) { - return true; - } - Piece targetPiece = board.getPiece(target); - return sourcePiece.isEnemy(targetPiece); - } - - public abstract boolean movable(final Position source, final Position target, final Board board); -} diff --git a/src/main/java/chess/domain/strategy/move/PawnMoveStrategy.java b/src/main/java/chess/domain/strategy/move/PawnMoveStrategy.java deleted file mode 100644 index 51152f41ea2..00000000000 --- a/src/main/java/chess/domain/strategy/move/PawnMoveStrategy.java +++ /dev/null @@ -1,49 +0,0 @@ -package chess.domain.strategy.move; - -import chess.domain.board.Board; -import chess.domain.piece.Piece; -import chess.domain.piece.Team; -import chess.domain.position.Position; - -public final class PawnMoveStrategy extends MoveStrategy { - private static final int WHITE_POSITION = 2; - private static final int BLACK_POSITION = 7; - - @Override - public boolean movable(final Position source, final Position target, final Board board) { - if (isSamePosition(source, target)) { - return false; - } - - int fileGap = source.calculateFileGap(target); - int rankGap = source.calculateRankGap(target); - - Piece sourcePiece = board.getPiece(source); - Piece targetPiece = board.getPiece(target); - Team pawnTeam = sourcePiece.getTeam(); - - if (pawnTeam.isWhite()) { - if (fileGap == 0 && rankGap == -1) { - return board.isEmpty(target); - } - if (fileGap == 0 && rankGap == -2) { - return source.getRank() == WHITE_POSITION; - } - if (Math.abs(fileGap) == 1 && rankGap == -1) { - return !board.isEmpty(target) && sourcePiece.isEnemy(targetPiece); - } - } - if (!pawnTeam.isWhite()) { - if (fileGap == 0 && rankGap == 1) { - return board.isEmpty(target); - } - if (fileGap == 0 && rankGap == 2) { - return source.getRank() == BLACK_POSITION; - } - if (Math.abs(fileGap) == 1 && rankGap == 1) { - return !board.isEmpty(target) && sourcePiece.isEnemy(targetPiece); - } - } - return false; - } -} \ No newline at end of file diff --git a/src/main/java/chess/domain/strategy/move/QueenMoveStrategy.java b/src/main/java/chess/domain/strategy/move/QueenMoveStrategy.java deleted file mode 100644 index 06b05f8db8b..00000000000 --- a/src/main/java/chess/domain/strategy/move/QueenMoveStrategy.java +++ /dev/null @@ -1,12 +0,0 @@ -package chess.domain.strategy.move; - -import chess.domain.board.Board; -import chess.domain.position.Position; - -public final class QueenMoveStrategy extends MoveStrategy { - @Override - public boolean movable(final Position source, final Position target, final Board board) { - return new RookMoveStrategy().movable(source, target, board) - || new BishopMoveStrategy().movable(source, target, board); - } -} \ No newline at end of file diff --git a/src/main/java/chess/domain/strategy/move/RookMoveStrategy.java b/src/main/java/chess/domain/strategy/move/RookMoveStrategy.java deleted file mode 100644 index 91f0bc112c3..00000000000 --- a/src/main/java/chess/domain/strategy/move/RookMoveStrategy.java +++ /dev/null @@ -1,20 +0,0 @@ -package chess.domain.strategy.move; - -import chess.domain.board.Board; -import chess.domain.position.Position; - -public final class RookMoveStrategy extends MoveStrategy { - @Override - public boolean movable(final Position source, final Position target, final Board board) { - if (isSamePosition(source, target)) { - return false; - } - - int fileGap = Math.abs(source.calculateFileGap(target)); - int rankGap = Math.abs(source.calculateRankGap(target)); - - return ((fileGap > 0 && rankGap == 0) || (fileGap == 0 && rankGap > 0)) - && checkObstacle(source, target, board) - && checkTarget(source, target, board); - } -} diff --git a/src/main/java/chess/view/ConsoleInputView.java b/src/main/java/chess/view/ConsoleInputView.java index caf9c36fe07..0649abe99fb 100644 --- a/src/main/java/chess/view/ConsoleInputView.java +++ b/src/main/java/chess/view/ConsoleInputView.java @@ -11,7 +11,7 @@ public String askChessRun() { System.out.println("> 게임 시작 : start"); System.out.println("> 게임 종료 : end"); System.out.println("> 게임 이동 : move source위치 target위치 - 예. move b2 b3"); - return askGameCommand(); + return SCANNER.nextLine(); } @Override diff --git a/src/main/java/chess/view/InputView.java b/src/main/java/chess/view/InputView.java index adb656d5da3..d3a8f06a520 100644 --- a/src/main/java/chess/view/InputView.java +++ b/src/main/java/chess/view/InputView.java @@ -2,5 +2,6 @@ public interface InputView { String askChessRun(); + String askGameCommand(); } diff --git a/src/main/java/chess/view/OutputView.java b/src/main/java/chess/view/OutputView.java index 1399b824401..5869d4291fd 100644 --- a/src/main/java/chess/view/OutputView.java +++ b/src/main/java/chess/view/OutputView.java @@ -7,6 +7,8 @@ public interface OutputView { void printBoard(List positions, Map board); + void printStatus(double calculateScore, Team team); + void printWinner(Team team); } diff --git a/src/test/java/chess/domain/ChessRunnerTest.java b/src/test/java/chess/domain/ChessRunnerTest.java index 093fd56c2b9..e311062b9ee 100644 --- a/src/test/java/chess/domain/ChessRunnerTest.java +++ b/src/test/java/chess/domain/ChessRunnerTest.java @@ -22,11 +22,35 @@ void validateCurrentTeam() { .hasMessage("현재 차례가 아닙니다."); } - @DisplayName("이동할 수 없는 곳일 때 에러 메시지 출력") + @DisplayName("같은 위치로 이동할 때 에러 메시지 출력") + @Test + void validateSamePosition() { + assertThatThrownBy(() -> chessRunner.update("a2", "a2")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("같은 위치로 이동할 수 없습니다."); + } + + @DisplayName("선택한 기물에 맞지 않는 목적지를 선택했을 때 에레 메시지 출력") @Test void validateMovable() { - assertThatThrownBy(() -> chessRunner.update("a1", "a2")) //화이트 팀 룩 이동 + assertThatThrownBy(() -> chessRunner.update("a1", "b2")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("선택한 기물이 이동할 수 없는 곳입니다."); + } + + @DisplayName("경로 사이에 장애물이 있을 때 에러 메시지 출력") + @Test + void validateObstacle() { + assertThatThrownBy(() -> chessRunner.update("a1", "a3")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("경로 사이에 장애물이 있습니다."); + } + + @DisplayName("잘못된 목적지를 선택했을 때 에러 메시지 출력") + @Test + void validateTarget() { + assertThatThrownBy(() -> chessRunner.update("a1", "a2")) .isInstanceOf(IllegalArgumentException.class) - .hasMessage("이동할 수 없는 곳입니다."); + .hasMessage("목적지가 잘못되었습니다."); } } \ No newline at end of file diff --git a/src/test/java/chess/domain/board/BoardTest.java b/src/test/java/chess/domain/board/BoardTest.java index 9a0e11c066b..f932e6b1a32 100644 --- a/src/test/java/chess/domain/board/BoardTest.java +++ b/src/test/java/chess/domain/board/BoardTest.java @@ -1,8 +1,6 @@ package chess.domain.board; -import chess.domain.piece.Piece; -import chess.domain.piece.PieceType; -import chess.domain.piece.Team; +import chess.domain.piece.*; import chess.domain.position.Position; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.DisplayName; @@ -20,16 +18,17 @@ void updateAtEmptyBoard() { Position target = Position.of("a3"); board.updateBoard(source, target); - Assertions.assertThat(board.getPiece(source)).isNull(); - Assertions.assertThat(board.getPiece(target)).isNotNull(); + Assertions.assertThatThrownBy(() -> { + board.getPiece(source); + }).isInstanceOf(IllegalArgumentException.class); Assertions.assertThat(board.getPiece(target)).isInstanceOf(Piece.class); } @DisplayName("상대 편으로 말 이동") @Test void updateAtEnemy() { - Piece rook = new Piece(PieceType.ROOK, Team.WHITE); - Piece pawn = new Piece(PieceType.PAWN, Team.BLACK); + Piece rook = new Rook(PieceType.ROOK, Team.WHITE); + Piece pawn = new Pawn(PieceType.PAWN, Team.BLACK); Map entry = new HashMap<>(); Position source = Position.of("a2"); Position target = Position.of("a3"); @@ -38,7 +37,9 @@ void updateAtEnemy() { Board board = new Board(entry); board.updateBoard(source, target); - Assertions.assertThat(board.getPiece(source)).isNull(); + Assertions.assertThatThrownBy(() -> { + board.getPiece(source); + }).isInstanceOf(IllegalArgumentException.class); Assertions.assertThat(board.getPiece(target)).isNotNull(); Assertions.assertThat(board.getPiece(target)).isInstanceOf(Piece.class); } @@ -47,16 +48,16 @@ void updateAtEnemy() { @Test void checkWinnerTest() { Map whiteKing = new HashMap<>(); - whiteKing.put(Position.of("a3"), new Piece(PieceType.KING, Team.WHITE)); + whiteKing.put(Position.of("a3"), new King(PieceType.KING, Team.WHITE)); Board whiteWinBoard = new Board(whiteKing); Map blackKing = new HashMap<>(); - blackKing.put(Position.of("b4"), new Piece(PieceType.KING, Team.BLACK)); + blackKing.put(Position.of("b4"), new King(PieceType.KING, Team.BLACK)); Board blackWinBoard = new Board(blackKing); Map bothKing = new HashMap<>(); - bothKing.put(Position.of("a5"), new Piece(PieceType.KING, Team.BLACK)); - bothKing.put(Position.of("b7"), new Piece(PieceType.KING, Team.WHITE)); + bothKing.put(Position.of("a5"), new King(PieceType.KING, Team.BLACK)); + bothKing.put(Position.of("b7"), new King(PieceType.KING, Team.WHITE)); Board drawBoard = new Board(bothKing); Assertions.assertThat(whiteWinBoard.checkWinner()).isEqualTo(Team.WHITE); @@ -81,7 +82,9 @@ void getPieceTest() { Board board = new Board(); Assertions.assertThat(board.getPiece(Position.of("a2"))).isInstanceOf(Piece.class); - Assertions.assertThat(board.getPiece(Position.of("a3"))).isNull(); + Assertions.assertThatThrownBy(() -> { + board.getPiece(Position.of("a3")); + }).isInstanceOf(IllegalArgumentException.class); } @DisplayName("같은 세로줄에 폰이 없을 때 점수 계산") @@ -89,19 +92,19 @@ void getPieceTest() { void calculateScoreWithoutSameFilePawnTest() { Board board = new Board(); - Assertions.assertThat(board.calculateScore(Team.WHITE)).isEqualTo(38d); - Assertions.assertThat(board.calculateScore(Team.BLACK)).isEqualTo(38d); + Assertions.assertThat(board.calculateScore(Team.WHITE)).extracting("boardScore").isEqualTo(38d); + Assertions.assertThat(board.calculateScore(Team.BLACK)).extracting("boardScore").isEqualTo(38d); } @DisplayName("같은 세로줄에 폰이 있을 때 점수 계산") @Test void calculateScoreWithSameFilePawn() { Map sameFilePawn = new HashMap<>(); - sameFilePawn.put(Position.of("a3"), new Piece(PieceType.PAWN, Team.WHITE)); - sameFilePawn.put(Position.of("a4"), new Piece(PieceType.PAWN, Team.WHITE)); - sameFilePawn.put(Position.of("a5"), new Piece(PieceType.PAWN, Team.WHITE)); + sameFilePawn.put(Position.of("a3"), new Pawn(PieceType.PAWN, Team.WHITE)); + sameFilePawn.put(Position.of("a4"), new Pawn(PieceType.PAWN, Team.WHITE)); + sameFilePawn.put(Position.of("a5"), new Pawn(PieceType.PAWN, Team.WHITE)); Board board = new Board(sameFilePawn); - Assertions.assertThat(board.calculateScore(Team.WHITE)).isEqualTo(1.5d); + Assertions.assertThat(board.calculateScore(Team.WHITE)).extracting("boardScore").isEqualTo(1.5d); } } diff --git a/src/test/java/chess/domain/piece/PieceTest.java b/src/test/java/chess/domain/piece/PieceTest.java index 088f7bc1eab..926051f7da8 100644 --- a/src/test/java/chess/domain/piece/PieceTest.java +++ b/src/test/java/chess/domain/piece/PieceTest.java @@ -9,8 +9,8 @@ class PieceTest { @DisplayName("팀 별 대소문자로 출력") @Test void toSymbol() { - Piece whitePiece = new Piece(PieceType.BISHOP, Team.WHITE); - Piece blackPiece = new Piece(PieceType.BISHOP, Team.BLACK); + Piece whitePiece = new Bishop(PieceType.BISHOP, Team.WHITE); + Piece blackPiece = new Bishop(PieceType.BISHOP, Team.BLACK); assertThat(whitePiece.toSymbol()).isEqualTo("b"); assertThat(blackPiece.toSymbol()).isEqualTo("B"); } @@ -18,16 +18,16 @@ void toSymbol() { @DisplayName("피스의 팀 구분") @Test void isEnemy() { - Piece whitePiece = new Piece(PieceType.KNIGHT, Team.WHITE); - Piece blackPiece = new Piece(PieceType.KNIGHT, Team.BLACK); + Piece whitePiece = new Knight(PieceType.KNIGHT, Team.WHITE); + Piece blackPiece = new Knight(PieceType.KNIGHT, Team.BLACK); assertThat(whitePiece.isEnemy(blackPiece)).isTrue(); } @DisplayName("피스가 흰 팀의 킹인지 테스트") @Test void isWhiteKing() { - Piece whiteKing = new Piece(PieceType.KING, Team.WHITE); - Piece blackBishop = new Piece(PieceType.BISHOP, Team.BLACK); + Piece whiteKing = new King(PieceType.KING, Team.WHITE); + Piece blackBishop = new Bishop(PieceType.BISHOP, Team.BLACK); assertThat(whiteKing.isWhiteKing()).isTrue(); assertThat(blackBishop.isWhiteKing()).isFalse(); } @@ -35,8 +35,8 @@ void isWhiteKing() { @DisplayName("피스가 검은 팀의 킹인지 테스트") @Test void isBlackKing() { - Piece blackKing = new Piece(PieceType.KING, Team.BLACK); - Piece whiteBishop = new Piece(PieceType.BISHOP, Team.WHITE); + Piece blackKing = new King(PieceType.KING, Team.BLACK); + Piece whiteBishop = new Bishop(PieceType.BISHOP, Team.WHITE); assertThat(blackKing.isBlackKing()).isTrue(); assertThat(whiteBishop.isBlackKing()).isFalse(); } @@ -44,8 +44,8 @@ void isBlackKing() { @DisplayName("피스가 폰인지 테스트") @Test void isPawn() { - Piece whitePawn = new Piece(PieceType.PAWN, Team.WHITE); - Piece blackQueen = new Piece(PieceType.QUEEN, Team.BLACK); + Piece whitePawn = new Pawn(PieceType.PAWN, Team.WHITE); + Piece blackQueen = new Queen(PieceType.QUEEN, Team.BLACK); assertThat(whitePawn.isPawn()).isTrue(); assertThat(blackQueen.isPawn()).isFalse(); } diff --git a/src/test/java/chess/domain/piece/TeamTest.java b/src/test/java/chess/domain/piece/TeamTest.java index 6578588c4a4..e792ec8643a 100644 --- a/src/test/java/chess/domain/piece/TeamTest.java +++ b/src/test/java/chess/domain/piece/TeamTest.java @@ -1,17 +1,20 @@ package chess.domain.piece; -import chess.domain.ChessRunner; +import org.assertj.core.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; - class TeamTest { @DisplayName("팀 순서 변경 테스트") @Test void changeTeam() { - ChessRunner chessRunner = new ChessRunner(); - Team nextTeam = Team.changeTeam(chessRunner.getCurrentTeam()); - assertThat(nextTeam.isSameTeamWith(Team.BLACK)).isTrue(); + Team blackTeam = Team.BLACK; + Team whiteTeam = Team.WHITE; + + Team blackExpected = blackTeam.changeTeam(); + Team whiteExpected = whiteTeam.changeTeam(); + + Assertions.assertThat(blackExpected).isEqualTo(Team.WHITE); + Assertions.assertThat(whiteExpected).isEqualTo(Team.BLACK); } } \ No newline at end of file diff --git a/src/test/java/chess/domain/strategy/move/direction/DirectionTest.java b/src/test/java/chess/domain/strategy/direction/DirectionTest.java similarity index 98% rename from src/test/java/chess/domain/strategy/move/direction/DirectionTest.java rename to src/test/java/chess/domain/strategy/direction/DirectionTest.java index 6e099801ded..9c160a57849 100644 --- a/src/test/java/chess/domain/strategy/move/direction/DirectionTest.java +++ b/src/test/java/chess/domain/strategy/direction/DirectionTest.java @@ -1,4 +1,4 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; import org.junit.jupiter.api.DisplayName; diff --git a/src/test/java/chess/domain/strategy/move/direction/DownStrategyTest.java b/src/test/java/chess/domain/strategy/direction/DownStrategyTest.java similarity index 94% rename from src/test/java/chess/domain/strategy/move/direction/DownStrategyTest.java rename to src/test/java/chess/domain/strategy/direction/DownStrategyTest.java index 60eea0efeb5..95c10219872 100644 --- a/src/test/java/chess/domain/strategy/move/direction/DownStrategyTest.java +++ b/src/test/java/chess/domain/strategy/direction/DownStrategyTest.java @@ -1,4 +1,4 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; import org.assertj.core.api.Assertions; diff --git a/src/test/java/chess/domain/strategy/move/direction/LeftDownStrategyTest.java b/src/test/java/chess/domain/strategy/direction/LeftDownStrategyTest.java similarity index 94% rename from src/test/java/chess/domain/strategy/move/direction/LeftDownStrategyTest.java rename to src/test/java/chess/domain/strategy/direction/LeftDownStrategyTest.java index 7b0ccb44a14..662a64c0ed8 100644 --- a/src/test/java/chess/domain/strategy/move/direction/LeftDownStrategyTest.java +++ b/src/test/java/chess/domain/strategy/direction/LeftDownStrategyTest.java @@ -1,4 +1,4 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; import org.assertj.core.api.Assertions; diff --git a/src/test/java/chess/domain/strategy/move/direction/LeftStrategyTest.java b/src/test/java/chess/domain/strategy/direction/LeftStrategyTest.java similarity index 94% rename from src/test/java/chess/domain/strategy/move/direction/LeftStrategyTest.java rename to src/test/java/chess/domain/strategy/direction/LeftStrategyTest.java index 8b27066e7f4..a8c126e60c2 100644 --- a/src/test/java/chess/domain/strategy/move/direction/LeftStrategyTest.java +++ b/src/test/java/chess/domain/strategy/direction/LeftStrategyTest.java @@ -1,4 +1,4 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; import org.assertj.core.api.Assertions; diff --git a/src/test/java/chess/domain/strategy/move/direction/LeftUpStrategyTest.java b/src/test/java/chess/domain/strategy/direction/LeftUpStrategyTest.java similarity index 94% rename from src/test/java/chess/domain/strategy/move/direction/LeftUpStrategyTest.java rename to src/test/java/chess/domain/strategy/direction/LeftUpStrategyTest.java index 8d3582c09c1..22689bd2bfc 100644 --- a/src/test/java/chess/domain/strategy/move/direction/LeftUpStrategyTest.java +++ b/src/test/java/chess/domain/strategy/direction/LeftUpStrategyTest.java @@ -1,4 +1,4 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; import org.assertj.core.api.Assertions; diff --git a/src/test/java/chess/domain/strategy/move/direction/RightDownStrategyTest.java b/src/test/java/chess/domain/strategy/direction/RightDownStrategyTest.java similarity index 94% rename from src/test/java/chess/domain/strategy/move/direction/RightDownStrategyTest.java rename to src/test/java/chess/domain/strategy/direction/RightDownStrategyTest.java index 196e8560276..38d160091d5 100644 --- a/src/test/java/chess/domain/strategy/move/direction/RightDownStrategyTest.java +++ b/src/test/java/chess/domain/strategy/direction/RightDownStrategyTest.java @@ -1,4 +1,4 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; import org.assertj.core.api.Assertions; diff --git a/src/test/java/chess/domain/strategy/move/direction/RightStrategyTest.java b/src/test/java/chess/domain/strategy/direction/RightStrategyTest.java similarity index 94% rename from src/test/java/chess/domain/strategy/move/direction/RightStrategyTest.java rename to src/test/java/chess/domain/strategy/direction/RightStrategyTest.java index 0487ca15540..b77f11878ec 100644 --- a/src/test/java/chess/domain/strategy/move/direction/RightStrategyTest.java +++ b/src/test/java/chess/domain/strategy/direction/RightStrategyTest.java @@ -1,4 +1,4 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; import org.assertj.core.api.Assertions; diff --git a/src/test/java/chess/domain/strategy/move/direction/RightUpStrategyTest.java b/src/test/java/chess/domain/strategy/direction/RightUpStrategyTest.java similarity index 94% rename from src/test/java/chess/domain/strategy/move/direction/RightUpStrategyTest.java rename to src/test/java/chess/domain/strategy/direction/RightUpStrategyTest.java index c4903e7303a..616ed9fbb94 100644 --- a/src/test/java/chess/domain/strategy/move/direction/RightUpStrategyTest.java +++ b/src/test/java/chess/domain/strategy/direction/RightUpStrategyTest.java @@ -1,4 +1,4 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; import org.assertj.core.api.Assertions; diff --git a/src/test/java/chess/domain/strategy/move/direction/UpStrategyTest.java b/src/test/java/chess/domain/strategy/direction/UpStrategyTest.java similarity index 94% rename from src/test/java/chess/domain/strategy/move/direction/UpStrategyTest.java rename to src/test/java/chess/domain/strategy/direction/UpStrategyTest.java index 8acb305c8c1..4999a795810 100644 --- a/src/test/java/chess/domain/strategy/move/direction/UpStrategyTest.java +++ b/src/test/java/chess/domain/strategy/direction/UpStrategyTest.java @@ -1,4 +1,4 @@ -package chess.domain.strategy.move.direction; +package chess.domain.strategy.direction; import chess.domain.position.Position; import org.assertj.core.api.Assertions; diff --git a/src/test/java/chess/domain/strategy/move/BishopMoveStrategyTest.java b/src/test/java/chess/domain/strategy/move/BishopMoveStrategyTest.java deleted file mode 100644 index 6bdeb3df2ca..00000000000 --- a/src/test/java/chess/domain/strategy/move/BishopMoveStrategyTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package chess.domain.strategy.move; - -import chess.domain.board.Board; -import chess.domain.piece.Piece; -import chess.domain.piece.PieceType; -import chess.domain.piece.Team; -import chess.domain.position.Position; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import java.util.HashMap; -import java.util.Map; - -public class BishopMoveStrategyTest { - private MoveStrategy bishopStrategy; - private Board board; - - @BeforeEach - private void setUp() { - bishopStrategy = new BishopMoveStrategy(); - Map emptyBoard = new HashMap<>(); - board = new Board(emptyBoard); - } - - @DisplayName("비숍의 우 상단 대각 이동") - @Test - void rightUpTest() { - Position source = Position.of("a1"); - Position target = Position.of("e5"); - - Assertions.assertThat(bishopStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("비숍의 우 하단 대각 이동") - @Test - void rightDownTest() { - Position source = Position.of("a7"); - Position target = Position.of("e3"); - - Assertions.assertThat(bishopStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("비숍의 좌 상단 대각 이동") - @Test - void leftUpTest() { - Position source = Position.of("g1"); - Position target = Position.of("c5"); - - Assertions.assertThat(bishopStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("비숍의 좌 하단 대각 이동") - @Test - void leftDownTest() { - Position source = Position.of("g7"); - Position target = Position.of("c3"); - - Assertions.assertThat(bishopStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("타겟 위치에 적이 있을 때 이동") - @Test - void moveWhenEnemyTest() { - Piece bishop = new Piece(PieceType.BISHOP, Team.BLACK); - Piece enemy = new Piece(PieceType.PAWN, Team.WHITE); - Position source = Position.of("a1"); - Position target = Position.of("e5"); - Map enemyEntry = new HashMap<>(); - enemyEntry.put(source, bishop); - enemyEntry.put(target, enemy); - Board enemyBoard = new Board(enemyEntry); - - Assertions.assertThat(bishopStrategy.movable(source, target, enemyBoard)).isTrue(); - } -} diff --git a/src/test/java/chess/domain/strategy/move/KingMoveStrategyTest.java b/src/test/java/chess/domain/strategy/move/KingMoveStrategyTest.java deleted file mode 100644 index 0f54b0d7e69..00000000000 --- a/src/test/java/chess/domain/strategy/move/KingMoveStrategyTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package chess.domain.strategy.move; - -import chess.domain.board.Board; -import chess.domain.piece.Piece; -import chess.domain.piece.PieceType; -import chess.domain.piece.Team; -import chess.domain.position.Position; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import java.util.HashMap; -import java.util.Map; - -public class KingMoveStrategyTest { - private MoveStrategy kingStrategy; - - @BeforeEach - private void setUp() { - kingStrategy = new KingMoveStrategy(); - } - - @DisplayName("킹의 이동 가능 위치에 대해 이동 테스트") - @Test - void moveTest() { - Map emptyBoard = new HashMap<>(); - Board board = new Board(emptyBoard); - Position source = Position.of("d4"); - - Position up = Position.of("d5"); - Position down = Position.of("d3"); - Position left = Position.of("c4"); - Position right = Position.of("e4"); - Position rightUp = Position.of("e5"); - Position rightDown = Position.of("e3"); - Position leftUp = Position.of("c5"); - Position leftDown = Position.of("c3"); - - Assertions.assertThat(kingStrategy.movable(source, up, board)).isTrue(); - Assertions.assertThat(kingStrategy.movable(source, down, board)).isTrue(); - Assertions.assertThat(kingStrategy.movable(source, left, board)).isTrue(); - Assertions.assertThat(kingStrategy.movable(source, right, board)).isTrue(); - Assertions.assertThat(kingStrategy.movable(source, rightUp, board)).isTrue(); - Assertions.assertThat(kingStrategy.movable(source, rightDown, board)).isTrue(); - Assertions.assertThat(kingStrategy.movable(source, leftUp, board)).isTrue(); - Assertions.assertThat(kingStrategy.movable(source, leftDown, board)).isTrue(); - } - - @DisplayName("타겟 위치에 적이 있을 때 이동") - @Test - void moveWhenEnemyTest() { - Piece king = new Piece(PieceType.KING, Team.BLACK); - Piece enemy = new Piece(PieceType.PAWN, Team.WHITE); - Position source = Position.of("d4"); - Position target = Position.of("e5"); - Map enemyEntry = new HashMap<>(); - enemyEntry.put(source, king); - enemyEntry.put(target, enemy); - Board enemyBoard = new Board(enemyEntry); - - Assertions.assertThat(kingStrategy.movable(source, target, enemyBoard)).isTrue(); - } -} diff --git a/src/test/java/chess/domain/strategy/move/KnightMoveStrategyTest.java b/src/test/java/chess/domain/strategy/move/KnightMoveStrategyTest.java deleted file mode 100644 index 84bcf4d3aa8..00000000000 --- a/src/test/java/chess/domain/strategy/move/KnightMoveStrategyTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package chess.domain.strategy.move; - -import chess.domain.board.Board; -import chess.domain.piece.Piece; -import chess.domain.piece.PieceType; -import chess.domain.piece.Team; -import chess.domain.position.Position; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import java.util.HashMap; -import java.util.Map; - -public class KnightMoveStrategyTest { - private MoveStrategy knightStrategy; - - @BeforeEach - private void setUp() { - knightStrategy = new KnightMoveStrategy(); - } - - @DisplayName("나이트의 이동 가능 위치에 이동") - @Test - void moveTest() { - Position source = Position.of("d4"); - Map emptyBoard = new HashMap<>(); - Board board = new Board(emptyBoard); - - Position upLeft = Position.of("c6"); - Position upRight = Position.of("e6"); - Position downLeft = Position.of("c2"); - Position downRight = Position.of("e2"); - Position leftUp = Position.of("b5"); - Position leftDown = Position.of("b3"); - Position rightUp = Position.of("f5"); - Position rightDown = Position.of("f3"); - - Assertions.assertThat(knightStrategy.movable(source, upLeft, board)).isTrue(); - Assertions.assertThat(knightStrategy.movable(source, upRight, board)).isTrue(); - Assertions.assertThat(knightStrategy.movable(source, downLeft, board)).isTrue(); - Assertions.assertThat(knightStrategy.movable(source, downRight, board)).isTrue(); - Assertions.assertThat(knightStrategy.movable(source, leftUp, board)).isTrue(); - Assertions.assertThat(knightStrategy.movable(source, leftDown, board)).isTrue(); - Assertions.assertThat(knightStrategy.movable(source, rightUp, board)).isTrue(); - Assertions.assertThat(knightStrategy.movable(source, rightDown, board)).isTrue(); - } - - @DisplayName("타겟 위치에 적이 있을 때 이동") - @Test - void moveWhenEnemyTest() { - Piece knight = new Piece(PieceType.KING, Team.BLACK); - Piece enemy = new Piece(PieceType.PAWN, Team.WHITE); - Position source = Position.of("d4"); - Position target = Position.of("e6"); - Map enemyEntry = new HashMap<>(); - enemyEntry.put(source, knight); - enemyEntry.put(target, enemy); - Board enemyBoard = new Board(enemyEntry); - - Assertions.assertThat(knightStrategy.movable(source, target, enemyBoard)).isTrue(); - } -} diff --git a/src/test/java/chess/domain/strategy/move/PawnMoveStrategyTest.java b/src/test/java/chess/domain/strategy/move/PawnMoveStrategyTest.java deleted file mode 100644 index 41e2d60050c..00000000000 --- a/src/test/java/chess/domain/strategy/move/PawnMoveStrategyTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package chess.domain.strategy.move; - -import chess.domain.board.Board; -import chess.domain.piece.Piece; -import chess.domain.piece.PieceType; -import chess.domain.piece.Team; -import chess.domain.position.Position; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import java.util.HashMap; -import java.util.Map; - -public class PawnMoveStrategyTest { - private MoveStrategy pawnStrategy; - - @BeforeEach - private void setUp() { - pawnStrategy = new PawnMoveStrategy(); -// Piece whitePawn = new Piece(PieceType.PAWN, Team.WHITE); -// Piece blackPawn = new Piece(PieceType.PAWN, Team.BLACK); -// Position whiteSource = Position.of("d4"); -// Position blackSource = Position.of("d3"); -// Map entry = new HashMap<>(); -// entry.put(whiteSource, whitePawn); -// entry.put(blackSource, blackPawn); -// board = new Board(entry); - } - - @DisplayName("폰이 시작 위치일 때 1칸 또는 2칸 이동") - @Test - void moveAtInitialPosition() { - Piece whitePawn = new Piece(PieceType.PAWN, Team.WHITE); - Piece blackPawn = new Piece(PieceType.PAWN, Team.BLACK); - Position whiteInitial = Position.of("a2"); - Position blackInitial = Position.of("a7"); - Map emptyBoard = new HashMap<>(); - emptyBoard.put(whiteInitial, whitePawn); - emptyBoard.put(blackInitial, blackPawn); - Board board = new Board(emptyBoard); - - Position whiteOne = Position.of("a3"); - Position whiteTwo = Position.of("a4"); - Position blackOne = Position.of("a6"); - Position blackTwo = Position.of("a5"); - - Assertions.assertThat(pawnStrategy.movable(whiteInitial, whiteOne, board)).isTrue(); - Assertions.assertThat(pawnStrategy.movable(whiteInitial, whiteTwo, board)).isTrue(); - Assertions.assertThat(pawnStrategy.movable(blackInitial, blackOne, board)).isTrue(); - Assertions.assertThat(pawnStrategy.movable(blackInitial, blackTwo, board)).isTrue(); - } - - @DisplayName("폰이 시작 위치가 아닐 때 1칸 전진") - @Test - void moveAtNoneInitialPosition() { - Piece whitePawn = new Piece(PieceType.PAWN, Team.WHITE); - Piece blackPawn = new Piece(PieceType.PAWN, Team.BLACK); - Position whiteSource = Position.of("a3"); - Position blackSource = Position.of("a6"); - Map emptyBoard = new HashMap<>(); - emptyBoard.put(whiteSource, whitePawn); - emptyBoard.put(blackSource, blackPawn); - Board board = new Board(emptyBoard); - - Position upTarget = Position.of("a4"); - Position downTarget = Position.of("a5"); - - Assertions.assertThat(pawnStrategy.movable(whiteSource, upTarget, board)).isTrue(); - Assertions.assertThat(pawnStrategy.movable(blackSource, downTarget, board)).isTrue(); - } - - @DisplayName("폰이 시작 위치가 아닐 때 대각선의 적을 공격 가능") - @Test - void moveDiagonalTest() { - Piece whitePawn = new Piece(PieceType.PAWN, Team.WHITE); - Piece whiteLeftEnemy = new Piece(PieceType.PAWN, Team.BLACK); - Piece whiteRightEnemy = new Piece(PieceType.PAWN, Team.BLACK); - - Piece blackPawn = new Piece(PieceType.PAWN, Team.BLACK); - Piece blackLeftEnemy = new Piece(PieceType.PAWN, Team.WHITE); - Piece blackRightEnemy = new Piece(PieceType.PAWN, Team.WHITE); - - Position whiteSource = Position.of("d3"); - Position whiteDiagonalLeft = Position.of("c4"); - Position whiteDiagonalRight = Position.of("e4"); - - Position blackSource = Position.of("d6"); - Position blackDiagonalLeft = Position.of("c5"); - Position blackDiagonalRight = Position.of("e5"); - - Map entry = new HashMap<>(); - entry.put(whiteSource, whitePawn); - entry.put(whiteDiagonalLeft, whiteLeftEnemy); - entry.put(whiteDiagonalRight, whiteRightEnemy); - entry.put(blackSource, blackPawn); - entry.put(blackDiagonalLeft, blackLeftEnemy); - entry.put(blackDiagonalRight, blackRightEnemy); - Board board = new Board(entry); - - Assertions.assertThat(pawnStrategy.movable(whiteSource, whiteDiagonalLeft, board)).isTrue(); - Assertions.assertThat(pawnStrategy.movable(whiteSource, whiteDiagonalRight, board)).isTrue(); - Assertions.assertThat(pawnStrategy.movable(blackSource, blackDiagonalLeft, board)).isTrue(); - Assertions.assertThat(pawnStrategy.movable(blackSource, blackDiagonalRight, board)).isTrue(); - } -} diff --git a/src/test/java/chess/domain/strategy/move/QueenMoveStrategyTest.java b/src/test/java/chess/domain/strategy/move/QueenMoveStrategyTest.java deleted file mode 100644 index e1cc32da9fd..00000000000 --- a/src/test/java/chess/domain/strategy/move/QueenMoveStrategyTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package chess.domain.strategy.move; - -import chess.domain.board.Board; -import chess.domain.piece.Piece; -import chess.domain.piece.PieceType; -import chess.domain.piece.Team; -import chess.domain.position.Position; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import java.util.HashMap; -import java.util.Map; - -public class QueenMoveStrategyTest { - private MoveStrategy queenStrategy; - private Board board; - - @BeforeEach - private void setUp() { - queenStrategy = new QueenMoveStrategy(); - Map emptyBoard = new HashMap<>(); - board = new Board(emptyBoard); - } - - @DisplayName("퀸의 우 상단 대각 이동") - @Test - void rightUpTest() { - Position source = Position.of("a1"); - Position target = Position.of("e5"); - - Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("퀸의 우 하단 대각 이동") - @Test - void rightDownTest() { - Position source = Position.of("a7"); - Position target = Position.of("e3"); - - Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("퀸의 좌 상단 대각 이동") - @Test - void leftUpTest() { - Position source = Position.of("g1"); - Position target = Position.of("c5"); - - Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("퀸의 좌 하단 대각 이동") - @Test - void leftDownTest() { - Position source = Position.of("g7"); - Position target = Position.of("c3"); - - Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("퀸의 상단 직진 이동") - @Test - void upTest() { - Position source = Position.of("a1"); - Position target = Position.of("a6"); - - Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("퀸의 하단 직진 이동") - @Test - void downTest() { - Position source = Position.of("a6"); - Position target = Position.of("a1"); - - Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("퀸의 우측 직진 이동") - @Test - void rightTest() { - Position source = Position.of("a1"); - Position target = Position.of("g1"); - - Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("퀸의 좌측 직진 이동") - @Test - void leftTest() { - Position source = Position.of("g1"); - Position target = Position.of("a1"); - - Assertions.assertThat(queenStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("타겟 위치에 적이 있을 때 이동") - @Test - void moveWhenEnemyTest() { - Piece queen = new Piece(PieceType.QUEEN, Team.BLACK); - Piece enemy = new Piece(PieceType.PAWN, Team.WHITE); - Position source = Position.of("a1"); - Position target = Position.of("a6"); - Map enemyEntry = new HashMap<>(); - enemyEntry.put(source, queen); - enemyEntry.put(target, enemy); - Board enemyBoard = new Board(enemyEntry); - - Assertions.assertThat(queenStrategy.movable(source, target, enemyBoard)).isTrue(); - } -} diff --git a/src/test/java/chess/domain/strategy/move/RookMoveStrategyTest.java b/src/test/java/chess/domain/strategy/move/RookMoveStrategyTest.java deleted file mode 100644 index bf977aa2c90..00000000000 --- a/src/test/java/chess/domain/strategy/move/RookMoveStrategyTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package chess.domain.strategy.move; - -import chess.domain.board.Board; -import chess.domain.piece.Piece; -import chess.domain.piece.PieceType; -import chess.domain.piece.Team; -import chess.domain.position.Position; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import java.util.HashMap; -import java.util.Map; - -public class RookMoveStrategyTest { - private MoveStrategy rookStrategy; - private Board board; - - @BeforeEach - private void setUp() { - rookStrategy = new RookMoveStrategy(); - Map emptyBoard = new HashMap<>(); - board = new Board(emptyBoard); - } - - @DisplayName("룩의 상단 직진 이동") - @Test - void upTest() { - Position source = Position.of("a1"); - Position target = Position.of("a6"); - - Assertions.assertThat(rookStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("룩의 하단 직진 이동") - @Test - void downTest() { - Position source = Position.of("a6"); - Position target = Position.of("a1"); - - Assertions.assertThat(rookStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("룩의 우측 직진 이동") - @Test - void rightTest() { - Position source = Position.of("a1"); - Position target = Position.of("g1"); - - Assertions.assertThat(rookStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("룩의 좌측 직진 이동") - @Test - void leftTest() { - Position source = Position.of("g1"); - Position target = Position.of("a1"); - - Assertions.assertThat(rookStrategy.movable(source, target, board)).isTrue(); - } - - @DisplayName("타겟 위치에 적이 있을 때 이동 테스트") - @Test - void moveWhenEnemyTest() { - Piece rook = new Piece(PieceType.ROOK, Team.BLACK); - Piece enemy = new Piece(PieceType.PAWN, Team.WHITE); - Position source = Position.of("a1"); - Position target = Position.of("a6"); - Map enemyEntry = new HashMap<>(); - enemyEntry.put(source, rook); - enemyEntry.put(target, enemy); - Board enemyBoard = new Board(enemyEntry); - - Assertions.assertThat(rookStrategy.movable(source, target, enemyBoard)).isTrue(); - } -} From 8888b082d88f14f068106b6afdffb044c69ac3bf Mon Sep 17 00:00:00 2001 From: giantim Date: Tue, 31 Mar 2020 23:00:24 +0900 Subject: [PATCH 26/29] =?UTF-8?q?refactor:=20Dto=20=EC=B6=94=EA=B0=80=20/?= =?UTF-8?q?=20ChessRunner=20=EC=97=90=EC=84=9C=20Dto=20=EC=97=90=20?= =?UTF-8?q?=EC=A0=81=ED=95=A9=ED=95=9C=20=EA=B0=92=EC=9D=84=20=EB=84=98?= =?UTF-8?q?=EA=B2=A8=EC=A3=BC=EB=8F=84=EB=A1=9D=20=EB=A9=94=EC=84=9C?= =?UTF-8?q?=EB=93=9C=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/controller/EndController.java | 1 - src/main/java/chess/controller/GameController.java | 7 ++++--- src/main/java/chess/controller/MoveController.java | 2 +- .../java/chess/controller/StartController.java | 2 +- .../java/chess/controller/StatusController.java | 9 ++++++--- .../java/chess/controller/dto/BoardScoreDto.java | 13 +++++++++++++ src/main/java/chess/controller/dto/TeamDto.java | 13 +++++++++++++ src/main/java/chess/domain/ChessRunner.java | 14 ++++++++++---- src/main/java/chess/domain/board/BoardScore.java | 4 ++++ src/main/java/chess/domain/position/Position.java | 14 +++++++------- src/main/java/chess/view/ConsoleOutputView.java | 4 ++-- src/main/java/chess/view/OutputView.java | 2 +- src/test/java/chess/domain/board/BoardTest.java | 6 +++--- 13 files changed, 65 insertions(+), 26 deletions(-) create mode 100644 src/main/java/chess/controller/dto/BoardScoreDto.java create mode 100644 src/main/java/chess/controller/dto/TeamDto.java diff --git a/src/main/java/chess/controller/EndController.java b/src/main/java/chess/controller/EndController.java index 5447a5811c3..0beb80032d8 100644 --- a/src/main/java/chess/controller/EndController.java +++ b/src/main/java/chess/controller/EndController.java @@ -9,6 +9,5 @@ public EndController() { @Override public void execute(ChessRunner chessRunner, String input) { - return; } } diff --git a/src/main/java/chess/controller/GameController.java b/src/main/java/chess/controller/GameController.java index 1bab9902963..ce494b93043 100644 --- a/src/main/java/chess/controller/GameController.java +++ b/src/main/java/chess/controller/GameController.java @@ -3,11 +3,12 @@ import chess.controller.dto.BoardDto; import chess.controller.dto.PositionDto; import chess.domain.ChessRunner; -import chess.domain.board.Board; import chess.domain.position.Position; import chess.view.ConsoleOutputView; import chess.view.OutputView; +import java.util.Map; + public abstract class GameController { protected final OutputView outputView; @@ -15,8 +16,8 @@ public GameController() { this.outputView = new ConsoleOutputView(); } - protected void printBoard(final Board board) { - BoardDto boardDto = new BoardDto(board.parse()); + protected void printBoard(final Map board) { + BoardDto boardDto = new BoardDto(board); PositionDto positionDto = new PositionDto(Position.getPositions()); this.outputView.printBoard(positionDto.getPositions(), boardDto.get()); } diff --git a/src/main/java/chess/controller/MoveController.java b/src/main/java/chess/controller/MoveController.java index 5c13028fd18..4bc52b69329 100644 --- a/src/main/java/chess/controller/MoveController.java +++ b/src/main/java/chess/controller/MoveController.java @@ -22,6 +22,6 @@ public void execute(ChessRunner chessRunner, String input) { String source = commands[SOURCE_INDEX]; String target = commands[TARGET_INDEX]; chessRunner.update(source, target); - printBoard(chessRunner.getBoard()); + printBoard(chessRunner.getBoardEntities()); } } diff --git a/src/main/java/chess/controller/StartController.java b/src/main/java/chess/controller/StartController.java index 7ce8debfbac..d952290efec 100644 --- a/src/main/java/chess/controller/StartController.java +++ b/src/main/java/chess/controller/StartController.java @@ -9,6 +9,6 @@ public StartController() { @Override public void execute(ChessRunner chessRunner, String input) { - printBoard(chessRunner.getBoard()); + printBoard(chessRunner.getBoardEntities()); } } diff --git a/src/main/java/chess/controller/StatusController.java b/src/main/java/chess/controller/StatusController.java index c3443a15bc5..1b950eccbc9 100644 --- a/src/main/java/chess/controller/StatusController.java +++ b/src/main/java/chess/controller/StatusController.java @@ -1,5 +1,7 @@ package chess.controller; +import chess.controller.dto.BoardScoreDto; +import chess.controller.dto.TeamDto; import chess.domain.ChessRunner; public class StatusController extends GameController { @@ -9,8 +11,9 @@ public StatusController() { @Override public void execute(ChessRunner chessRunner, String input) { -// double score = chessRunner.calculateScore(); -// outputView.printStatus(score, chessRunner.getCurrentTeam()); - printBoard(chessRunner.getBoard()); + BoardScoreDto boardScoreDto = new BoardScoreDto(chessRunner.calculateScore()); + TeamDto teamDto = new TeamDto(chessRunner.getCurrentTeam()); + outputView.printStatus(boardScoreDto.getBoardScore(), teamDto.getTeamName()); + printBoard(chessRunner.getBoardEntities()); } } diff --git a/src/main/java/chess/controller/dto/BoardScoreDto.java b/src/main/java/chess/controller/dto/BoardScoreDto.java new file mode 100644 index 00000000000..d7e457a2076 --- /dev/null +++ b/src/main/java/chess/controller/dto/BoardScoreDto.java @@ -0,0 +1,13 @@ +package chess.controller.dto; + +public class BoardScoreDto { + private final double boardScore; + + public BoardScoreDto(double boardScore) { + this.boardScore = boardScore; + } + + public double getBoardScore() { + return boardScore; + } +} diff --git a/src/main/java/chess/controller/dto/TeamDto.java b/src/main/java/chess/controller/dto/TeamDto.java new file mode 100644 index 00000000000..073908e98f8 --- /dev/null +++ b/src/main/java/chess/controller/dto/TeamDto.java @@ -0,0 +1,13 @@ +package chess.controller.dto; + +public class TeamDto { + private final String teamName; + + public TeamDto(final String teamName) { + this.teamName = teamName; + } + + public String getTeamName() { + return teamName; + } +} diff --git a/src/main/java/chess/domain/ChessRunner.java b/src/main/java/chess/domain/ChessRunner.java index feebf2fdc9c..180715f61d4 100644 --- a/src/main/java/chess/domain/ChessRunner.java +++ b/src/main/java/chess/domain/ChessRunner.java @@ -8,6 +8,7 @@ import chess.domain.strategy.direction.Direction; import java.util.List; +import java.util.Map; public class ChessRunner { private Board board; @@ -86,12 +87,17 @@ public Team findWinner() { return this.board.checkWinner(); } - public BoardScore calculateScore() { - return board.calculateScore(this.currentTeam); + public double calculateScore() { + BoardScore boardScore = this.board.calculateScore(this.currentTeam); + return boardScore.getBoardScore(); } - public Team getCurrentTeam() { - return this.currentTeam; + public Map getBoardEntities() { + return this.board.parse(); + } + + public String getCurrentTeam() { + return this.currentTeam.name(); } public Board getBoard() { diff --git a/src/main/java/chess/domain/board/BoardScore.java b/src/main/java/chess/domain/board/BoardScore.java index 9525bd8ec69..fc46c94ffba 100644 --- a/src/main/java/chess/domain/board/BoardScore.java +++ b/src/main/java/chess/domain/board/BoardScore.java @@ -23,4 +23,8 @@ public BoardScore pawnStrategy(List> sameFilePawns) { } return this; } + + public double getBoardScore() { + return this.boardScore; + } } diff --git a/src/main/java/chess/domain/position/Position.java b/src/main/java/chess/domain/position/Position.java index 4ba4ddb7fd5..f0794eb275e 100644 --- a/src/main/java/chess/domain/position/Position.java +++ b/src/main/java/chess/domain/position/Position.java @@ -52,13 +52,6 @@ public static Position of(final int fileSymbol, final int rankSymbol) { return findPosition(File.of(fileSymbol), Rank.of(rankSymbol)); } - public static List getPositions() { - List parseResult = positions.stream() - .map(Position::toString) - .collect(Collectors.toList()); - return Collections.unmodifiableList(parseResult); - } - public int calculateFileGap(final Position target) { return this.file.compareTo(target.file); } @@ -67,6 +60,13 @@ public int calculateRankGap(final Position target) { return this.rank.getDifference(target.rank); } + public static List getPositions() { + List parseResult = positions.stream() + .map(Position::toString) + .collect(Collectors.toList()); + return Collections.unmodifiableList(parseResult); + } + public int getFile() { return this.file.getNumber(); } diff --git a/src/main/java/chess/view/ConsoleOutputView.java b/src/main/java/chess/view/ConsoleOutputView.java index b0cc85985cd..8aac91e3d1b 100644 --- a/src/main/java/chess/view/ConsoleOutputView.java +++ b/src/main/java/chess/view/ConsoleOutputView.java @@ -33,8 +33,8 @@ private String printPiece(String piece) { } @Override - public void printStatus(double calculateScore, Team team) { - System.out.println(String.format("%s 팀의 점수는 %.1f 점입니다.", team.name(), calculateScore)); + public void printStatus(double calculateScore, String teamName) { + System.out.println(String.format("%s 팀의 점수는 %.1f 점입니다.", teamName, calculateScore)); } @Override diff --git a/src/main/java/chess/view/OutputView.java b/src/main/java/chess/view/OutputView.java index 5869d4291fd..2a2d3c2b96c 100644 --- a/src/main/java/chess/view/OutputView.java +++ b/src/main/java/chess/view/OutputView.java @@ -8,7 +8,7 @@ public interface OutputView { void printBoard(List positions, Map board); - void printStatus(double calculateScore, Team team); + void printStatus(double calculateScore, String teamName); void printWinner(Team team); } diff --git a/src/test/java/chess/domain/board/BoardTest.java b/src/test/java/chess/domain/board/BoardTest.java index f932e6b1a32..f8bfd051ce5 100644 --- a/src/test/java/chess/domain/board/BoardTest.java +++ b/src/test/java/chess/domain/board/BoardTest.java @@ -92,8 +92,8 @@ void getPieceTest() { void calculateScoreWithoutSameFilePawnTest() { Board board = new Board(); - Assertions.assertThat(board.calculateScore(Team.WHITE)).extracting("boardScore").isEqualTo(38d); - Assertions.assertThat(board.calculateScore(Team.BLACK)).extracting("boardScore").isEqualTo(38d); + Assertions.assertThat(board.calculateScore(Team.WHITE).getBoardScore()).isEqualTo(38d); + Assertions.assertThat(board.calculateScore(Team.BLACK).getBoardScore()).isEqualTo(38d); } @DisplayName("같은 세로줄에 폰이 있을 때 점수 계산") @@ -105,6 +105,6 @@ void calculateScoreWithSameFilePawn() { sameFilePawn.put(Position.of("a5"), new Pawn(PieceType.PAWN, Team.WHITE)); Board board = new Board(sameFilePawn); - Assertions.assertThat(board.calculateScore(Team.WHITE)).extracting("boardScore").isEqualTo(1.5d); + Assertions.assertThat(board.calculateScore(Team.WHITE).getBoardScore()).isEqualTo(1.5d); } } From 08cbd7398bdad36ea8d4bbb319abc0cc59a52885 Mon Sep 17 00:00:00 2001 From: giantim Date: Tue, 31 Mar 2020 23:47:56 +0900 Subject: [PATCH 27/29] =?UTF-8?q?refactor:=20=EA=B2=8C=EC=9E=84=20?= =?UTF-8?q?=EC=A2=85=EB=A3=8C=20=EA=B2=BD=EC=9A=B0=EC=97=90=20=EB=94=B0?= =?UTF-8?q?=EB=9D=BC=20=EC=A0=90=EC=88=98=20=EC=B6=9C=EB=A0=A5=20=EB=A1=9C?= =?UTF-8?q?=EC=A7=81=20=EA=B5=AC=ED=98=84=20/=20=EA=B0=9D=EC=B2=B4=20null?= =?UTF-8?q?=20=EB=B0=98=ED=99=98=EC=9D=84=20Optional=20=EC=9D=84=20?= =?UTF-8?q?=EC=9D=B4=EC=9A=A9=ED=95=98=EB=8F=84=EB=A1=9D=20=EB=B3=80?= =?UTF-8?q?=EA=B2=BD=20/=20=EA=B0=81=20=EC=B2=B4=EC=8A=A4=20=EB=A7=90?= =?UTF-8?q?=EC=9D=84=20=EC=B4=88=EA=B8=B0=ED=99=94=20=ED=95=A0=EB=95=8C?= =?UTF-8?q?=EC=9D=98=20=EC=A0=95=EB=B3=B4=EB=A5=BC=20enum=20=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chess/controller/ChessController.java | 15 +++-- src/main/java/chess/domain/ChessRunner.java | 18 +++--- src/main/java/chess/domain/board/Board.java | 13 ++--- .../initialize/BishopInitializer.java | 32 +++++++--- .../strategy/initialize/KingInitializer.java | 28 +++++++-- .../initialize/KnightInitializer.java | 32 +++++++--- .../strategy/initialize/PawnInitializer.java | 58 ++++++++++++------- .../strategy/initialize/QueenInitializer.java | 28 +++++++-- .../strategy/initialize/RookInitializer.java | 32 +++++++--- .../java/chess/view/ConsoleOutputView.java | 6 +- src/main/java/chess/view/OutputView.java | 4 +- .../java/chess/domain/board/BoardTest.java | 9 ++- 12 files changed, 190 insertions(+), 85 deletions(-) diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index 0c45cd5ad61..f5bb64d8294 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -1,7 +1,7 @@ package chess.controller; +import chess.controller.dto.TeamDto; import chess.domain.ChessRunner; -import chess.domain.piece.Team; import chess.view.ConsoleInputView; import chess.view.ConsoleOutputView; import chess.view.InputView; @@ -26,7 +26,8 @@ public static void start() { private static void runChessGame(Command command, ChessRunner chessRunner) { do { command = validateExecute(command, chessRunner); - } while (!command.isEnd() && findWinner(chessRunner)); + } while (!command.isEnd() && !chessRunner.isEndChess()); + printWinner(chessRunner); } private static Command validateExecute(Command command, ChessRunner chessRunner) { @@ -41,12 +42,10 @@ private static Command validateExecute(Command command, ChessRunner chessRunner) return command; } - private static boolean findWinner(final ChessRunner chessRunner) { - Team winner = chessRunner.findWinner(); - if (winner != null) { - outputView.printWinner(winner); - return false; + private static void printWinner(ChessRunner chessRunner) { + if (chessRunner.isEndChess()) { + TeamDto teamDto = new TeamDto(chessRunner.getWinner()); + outputView.printWinner(teamDto.getTeamName()); } - return true; } } diff --git a/src/main/java/chess/domain/ChessRunner.java b/src/main/java/chess/domain/ChessRunner.java index 180715f61d4..4652a0e677b 100644 --- a/src/main/java/chess/domain/ChessRunner.java +++ b/src/main/java/chess/domain/ChessRunner.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.Map; +import java.util.Optional; public class ChessRunner { private Board board; @@ -50,7 +51,7 @@ private void checkUpdateBoard(Position sourcePosition, Position targetPosition, throw new IllegalArgumentException("경로 사이에 장애물이 있습니다."); } - if (!movableTarget(sourcePiece, targetPosition)) { + if (!isMovableTarget(sourcePiece, targetPosition)) { throw new IllegalArgumentException("목적지가 잘못되었습니다."); } } @@ -70,7 +71,7 @@ private boolean isEmptyPath(final Position sourcePosition, final Position target .allMatch(this.board::isEmpty); } - private boolean movableTarget(final Piece sourcePiece, final Position targetPosition) { + private boolean isMovableTarget(final Piece sourcePiece, final Position targetPosition) { Piece targetPiece = this.board.getPiece(targetPosition); return sourcePiece.isEnemy(targetPiece); } @@ -83,15 +84,15 @@ private void changeTeam() { this.currentTeam = this.currentTeam.changeTeam(); } - public Team findWinner() { - return this.board.checkWinner(); - } - public double calculateScore() { BoardScore boardScore = this.board.calculateScore(this.currentTeam); return boardScore.getBoardScore(); } + public boolean isEndChess() { + return this.board.getWinner().isPresent(); + } + public Map getBoardEntities() { return this.board.parse(); } @@ -100,7 +101,8 @@ public String getCurrentTeam() { return this.currentTeam.name(); } - public Board getBoard() { - return this.board; + public String getWinner() { + Optional winner = this.board.getWinner(); + return winner.map(Enum::name).orElseThrow(AssertionError::new); } } diff --git a/src/main/java/chess/domain/board/Board.java b/src/main/java/chess/domain/board/Board.java index 53188c00728..13ef182755a 100644 --- a/src/main/java/chess/domain/board/Board.java +++ b/src/main/java/chess/domain/board/Board.java @@ -5,10 +5,7 @@ import chess.domain.position.File; import chess.domain.position.Position; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.stream.Collectors; public class Board { @@ -53,14 +50,14 @@ private BoardScore calculatePawnScore(final Team team, BoardScore totalScore) { return totalScore; } - public Team checkWinner() { + public Optional getWinner() { if (checkWhiteKing() && !checkBlackKing()) { - return Team.WHITE; + return Optional.of(Team.WHITE); } if (!checkWhiteKing() && checkBlackKing()) { - return Team.BLACK; + return Optional.of(Team.BLACK); } - return null; + return Optional.empty(); } private boolean checkWhiteKing() { diff --git a/src/main/java/chess/domain/strategy/initialize/BishopInitializer.java b/src/main/java/chess/domain/strategy/initialize/BishopInitializer.java index 59fdbc8d981..de5017b6892 100644 --- a/src/main/java/chess/domain/strategy/initialize/BishopInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/BishopInitializer.java @@ -6,19 +6,37 @@ import chess.domain.piece.Team; import chess.domain.position.Position; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.stream.Collectors; public final class BishopInitializer implements InitializeStrategy { + private enum InitialBishop { + BLACK_LEFT(Position.of("c8"), new Bishop(PieceType.BISHOP, Team.BLACK)), + BLACK_RIGHT(Position.of("f8"), new Bishop(PieceType.BISHOP, Team.BLACK)), + WHITE_LEFT(Position.of("c1"), new Bishop(PieceType.BISHOP, Team.WHITE)), + WHITE_RIGHT(Position.of("f1"), new Bishop(PieceType.BISHOP, Team.WHITE)); + + private final Position position; + private final Piece piece; + + InitialBishop(Position position, Piece piece) { + this.position = position; + this.piece = piece; + } + + public static Map initializeBishops() { + Map bishops = Arrays.stream(values()) + .collect(Collectors.toMap(entry -> entry.position, entry -> entry.piece, + (e1, e2) -> e1, HashMap::new)); + return Collections.unmodifiableMap(bishops); + } + } + @Override public Map initialize() { - Map pieces = new HashMap<>(); - pieces.put(Position.of("c8"), new Bishop(PieceType.BISHOP, Team.BLACK)); - pieces.put(Position.of("c1"), new Bishop(PieceType.BISHOP, Team.WHITE)); - pieces.put(Position.of("f8"), new Bishop(PieceType.BISHOP, Team.BLACK)); - pieces.put(Position.of("f1"), new Bishop(PieceType.BISHOP, Team.WHITE)); - - return Collections.unmodifiableMap(pieces); + return InitialBishop.initializeBishops(); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/strategy/initialize/KingInitializer.java b/src/main/java/chess/domain/strategy/initialize/KingInitializer.java index 598495e1f75..caec8420870 100644 --- a/src/main/java/chess/domain/strategy/initialize/KingInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/KingInitializer.java @@ -6,17 +6,35 @@ import chess.domain.piece.Team; import chess.domain.position.Position; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.stream.Collectors; public final class KingInitializer implements InitializeStrategy { + private enum InitialKing { + BLACK_KING(Position.of("e8"), new King(PieceType.KING, Team.BLACK)), + WHITE_KING(Position.of("e1"), new King(PieceType.KING, Team.WHITE)); + + private final Position position; + private final Piece piece; + + InitialKing(Position position, Piece piece) { + this.position = position; + this.piece = piece; + } + + public static Map initializeKings() { + Map kings = Arrays.stream(values()) + .collect(Collectors.toMap(entry -> entry.position, entry -> entry.piece, + (e1, e2) -> e1, HashMap::new)); + return Collections.unmodifiableMap(kings); + } + } + @Override public Map initialize() { - Map pieces = new HashMap<>(); - pieces.put(Position.of("e8"), new King(PieceType.KING, Team.BLACK)); - pieces.put(Position.of("e1"), new King(PieceType.KING, Team.WHITE)); - - return Collections.unmodifiableMap(pieces); + return InitialKing.initializeKings(); } } diff --git a/src/main/java/chess/domain/strategy/initialize/KnightInitializer.java b/src/main/java/chess/domain/strategy/initialize/KnightInitializer.java index d2863dde2e1..fa95bb0823d 100644 --- a/src/main/java/chess/domain/strategy/initialize/KnightInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/KnightInitializer.java @@ -6,19 +6,37 @@ import chess.domain.piece.Team; import chess.domain.position.Position; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.stream.Collectors; public final class KnightInitializer implements InitializeStrategy { + private enum InitialKnight { + BLACK_LEFT(Position.of("b8"), new Knight(PieceType.KNIGHT, Team.BLACK)), + BLACK_RIGHT(Position.of("g8"), new Knight(PieceType.KNIGHT, Team.BLACK)), + WHITE_LEFT(Position.of("b1"), new Knight(PieceType.KNIGHT, Team.WHITE)), + WHITE_RIGHT(Position.of("g1"), new Knight(PieceType.KNIGHT, Team.WHITE)); + + private final Position position; + private final Piece piece; + + InitialKnight(Position position, Piece piece) { + this.position = position; + this.piece = piece; + } + + public static Map initializeKnights() { + Map knights = Arrays.stream(values()) + .collect(Collectors.toMap(entry -> entry.position, entry -> entry.piece, + (e1, e2) -> e1, HashMap::new)); + return Collections.unmodifiableMap(knights); + } + } + @Override public Map initialize() { - Map pieces = new HashMap<>(); - pieces.put(Position.of("b8"), new Knight(PieceType.KNIGHT, Team.BLACK)); - pieces.put(Position.of("b1"), new Knight(PieceType.KNIGHT, Team.WHITE)); - pieces.put(Position.of("g8"), new Knight(PieceType.KNIGHT, Team.BLACK)); - pieces.put(Position.of("g1"), new Knight(PieceType.KNIGHT, Team.WHITE)); - - return Collections.unmodifiableMap(pieces); + return InitialKnight.initializeKnights(); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/strategy/initialize/PawnInitializer.java b/src/main/java/chess/domain/strategy/initialize/PawnInitializer.java index e9296b8bc57..523acea9c0a 100644 --- a/src/main/java/chess/domain/strategy/initialize/PawnInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/PawnInitializer.java @@ -6,32 +6,50 @@ import chess.domain.piece.Team; import chess.domain.position.Position; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.stream.Collectors; public final class PawnInitializer implements InitializeStrategy { + private enum InitialPawn { + BLACK_A7(Position.of("a7"), new Pawn(PieceType.PAWN, Team.BLACK)), + BLACK_B7(Position.of("b7"), new Pawn(PieceType.PAWN, Team.BLACK)), + BLACK_C7(Position.of("c7"), new Pawn(PieceType.PAWN, Team.BLACK)), + BLACK_D7(Position.of("d7"), new Pawn(PieceType.PAWN, Team.BLACK)), + BLACK_E7(Position.of("e7"), new Pawn(PieceType.PAWN, Team.BLACK)), + BLACK_F7(Position.of("f7"), new Pawn(PieceType.PAWN, Team.BLACK)), + BLACK_G7(Position.of("g7"), new Pawn(PieceType.PAWN, Team.BLACK)), + BLACK_H7(Position.of("h7"), new Pawn(PieceType.PAWN, Team.BLACK)), + + WHITE_A2(Position.of("a2"), new Pawn(PieceType.PAWN, Team.WHITE)), + WHITE_B2(Position.of("b2"), new Pawn(PieceType.PAWN, Team.WHITE)), + WHITE_C2(Position.of("c2"), new Pawn(PieceType.PAWN, Team.WHITE)), + WHITE_D2(Position.of("d2"), new Pawn(PieceType.PAWN, Team.WHITE)), + WHITE_E2(Position.of("e2"), new Pawn(PieceType.PAWN, Team.WHITE)), + WHITE_F2(Position.of("f2"), new Pawn(PieceType.PAWN, Team.WHITE)), + WHITE_G2(Position.of("g2"), new Pawn(PieceType.PAWN, Team.WHITE)), + WHITE_H2(Position.of("h2"), new Pawn(PieceType.PAWN, Team.WHITE)); + + private final Position position; + private final Piece piece; + + InitialPawn(Position position, Piece piece) { + this.position = position; + this.piece = piece; + } + + public static Map initialPawns() { + Map pawns = Arrays.stream(values()) + .collect(Collectors.toMap(entry -> entry.position, entry -> entry.piece, + (e1, e2) -> e1, HashMap::new)); + return Collections.unmodifiableMap(pawns); + } + } + @Override public Map initialize() { - Map pieces = new HashMap<>(); - pieces.put(Position.of("a7"), new Pawn(PieceType.PAWN, Team.BLACK)); - pieces.put(Position.of("b7"), new Pawn(PieceType.PAWN, Team.BLACK)); - pieces.put(Position.of("c7"), new Pawn(PieceType.PAWN, Team.BLACK)); - pieces.put(Position.of("d7"), new Pawn(PieceType.PAWN, Team.BLACK)); - pieces.put(Position.of("e7"), new Pawn(PieceType.PAWN, Team.BLACK)); - pieces.put(Position.of("f7"), new Pawn(PieceType.PAWN, Team.BLACK)); - pieces.put(Position.of("g7"), new Pawn(PieceType.PAWN, Team.BLACK)); - pieces.put(Position.of("h7"), new Pawn(PieceType.PAWN, Team.BLACK)); - - pieces.put(Position.of("a2"), new Pawn(PieceType.PAWN, Team.WHITE)); - pieces.put(Position.of("b2"), new Pawn(PieceType.PAWN, Team.WHITE)); - pieces.put(Position.of("c2"), new Pawn(PieceType.PAWN, Team.WHITE)); - pieces.put(Position.of("d2"), new Pawn(PieceType.PAWN, Team.WHITE)); - pieces.put(Position.of("e2"), new Pawn(PieceType.PAWN, Team.WHITE)); - pieces.put(Position.of("f2"), new Pawn(PieceType.PAWN, Team.WHITE)); - pieces.put(Position.of("g2"), new Pawn(PieceType.PAWN, Team.WHITE)); - pieces.put(Position.of("h2"), new Pawn(PieceType.PAWN, Team.WHITE)); - - return Collections.unmodifiableMap(pieces); + return InitialPawn.initialPawns(); } } diff --git a/src/main/java/chess/domain/strategy/initialize/QueenInitializer.java b/src/main/java/chess/domain/strategy/initialize/QueenInitializer.java index 64ea4cfc49d..e23871b6bd9 100644 --- a/src/main/java/chess/domain/strategy/initialize/QueenInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/QueenInitializer.java @@ -6,17 +6,35 @@ import chess.domain.piece.Team; import chess.domain.position.Position; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.stream.Collectors; public final class QueenInitializer implements InitializeStrategy { + private enum InitialQueen { + BLACK_QUEEN(Position.of("d8"), new Queen(PieceType.QUEEN, Team.BLACK)), + WHITE_QUEEN(Position.of("d1"), new Queen(PieceType.QUEEN, Team.WHITE)); + + private final Position position; + private final Piece piece; + + InitialQueen(Position position, Piece piece) { + this.position = position; + this.piece = piece; + } + + public static Map initializeQueens() { + Map queens = Arrays.stream(values()) + .collect(Collectors.toMap(entry -> entry.position, entry -> entry.piece, + (e1, e2) -> e1, HashMap::new)); + return Collections.unmodifiableMap(queens); + } + } + @Override public Map initialize() { - Map pieces = new HashMap<>(); - pieces.put(Position.of("d8"), new Queen(PieceType.QUEEN, Team.BLACK)); - pieces.put(Position.of("d1"), new Queen(PieceType.QUEEN, Team.WHITE)); - - return Collections.unmodifiableMap(pieces); + return InitialQueen.initializeQueens(); } } \ No newline at end of file diff --git a/src/main/java/chess/domain/strategy/initialize/RookInitializer.java b/src/main/java/chess/domain/strategy/initialize/RookInitializer.java index efcfbe69b8f..8b351c3088d 100644 --- a/src/main/java/chess/domain/strategy/initialize/RookInitializer.java +++ b/src/main/java/chess/domain/strategy/initialize/RookInitializer.java @@ -6,19 +6,37 @@ import chess.domain.piece.Team; import chess.domain.position.Position; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.stream.Collectors; public final class RookInitializer implements InitializeStrategy { + private enum InitialRook { + BLACK_LEFT(Position.of("a8"), new Rook(PieceType.ROOK, Team.BLACK)), + BLACK_RIGHT(Position.of("h8"), new Rook(PieceType.ROOK, Team.BLACK)), + WHITE_LEFT(Position.of("a1"), new Rook(PieceType.ROOK, Team.WHITE)), + WHITE_RIGHT(Position.of("h1"), new Rook(PieceType.ROOK, Team.WHITE)); + + private final Position position; + private final Piece piece; + + InitialRook(Position position, Piece piece) { + this.position = position; + this.piece = piece; + } + + public static Map initializeRooks() { + Map rooks = Arrays.stream(values()) + .collect(Collectors.toMap(entry -> entry.position, entry -> entry.piece, + (e1, e2) -> e1, HashMap::new)); + return Collections.unmodifiableMap(rooks); + } + } + @Override public Map initialize() { - Map pieces = new HashMap<>(); - pieces.put(Position.of("a8"), new Rook(PieceType.ROOK, Team.BLACK)); - pieces.put(Position.of("a1"), new Rook(PieceType.ROOK, Team.WHITE)); - pieces.put(Position.of("h8"), new Rook(PieceType.ROOK, Team.BLACK)); - pieces.put(Position.of("h1"), new Rook(PieceType.ROOK, Team.WHITE)); - - return Collections.unmodifiableMap(pieces); + return InitialRook.initializeRooks(); } } \ No newline at end of file diff --git a/src/main/java/chess/view/ConsoleOutputView.java b/src/main/java/chess/view/ConsoleOutputView.java index 8aac91e3d1b..b85b029b013 100644 --- a/src/main/java/chess/view/ConsoleOutputView.java +++ b/src/main/java/chess/view/ConsoleOutputView.java @@ -1,7 +1,5 @@ package chess.view; -import chess.domain.piece.Team; - import java.util.List; import java.util.Map; @@ -38,7 +36,7 @@ public void printStatus(double calculateScore, String teamName) { } @Override - public void printWinner(Team team) { - System.out.println(String.format("%s 팀이 이겼습니다.", team.name())); + public void printWinner(String teamName) { + System.out.println(String.format("%s 팀이 이겼습니다.", teamName)); } } diff --git a/src/main/java/chess/view/OutputView.java b/src/main/java/chess/view/OutputView.java index 2a2d3c2b96c..155d5eaca09 100644 --- a/src/main/java/chess/view/OutputView.java +++ b/src/main/java/chess/view/OutputView.java @@ -1,7 +1,5 @@ package chess.view; -import chess.domain.piece.Team; - import java.util.List; import java.util.Map; @@ -10,5 +8,5 @@ public interface OutputView { void printStatus(double calculateScore, String teamName); - void printWinner(Team team); + void printWinner(String teamName); } diff --git a/src/test/java/chess/domain/board/BoardTest.java b/src/test/java/chess/domain/board/BoardTest.java index f8bfd051ce5..c1cb9c4df07 100644 --- a/src/test/java/chess/domain/board/BoardTest.java +++ b/src/test/java/chess/domain/board/BoardTest.java @@ -8,6 +8,7 @@ import java.util.HashMap; import java.util.Map; +import java.util.NoSuchElementException; public class BoardTest { @DisplayName("빈 칸으로 말 이동") @@ -60,9 +61,11 @@ void checkWinnerTest() { bothKing.put(Position.of("b7"), new King(PieceType.KING, Team.WHITE)); Board drawBoard = new Board(bothKing); - Assertions.assertThat(whiteWinBoard.checkWinner()).isEqualTo(Team.WHITE); - Assertions.assertThat(blackWinBoard.checkWinner()).isEqualTo(Team.BLACK); - Assertions.assertThat(drawBoard.checkWinner()).isNull(); + Assertions.assertThat(whiteWinBoard.getWinner().get()).isEqualTo(Team.WHITE); + Assertions.assertThat(blackWinBoard.getWinner().get()).isEqualTo(Team.BLACK); + Assertions.assertThatThrownBy(() -> { + drawBoard.getWinner().get(); + }).isInstanceOf(NoSuchElementException.class); } @DisplayName("지정한 칸이 비어있는지 판단") From bdf1a0a509de22b62819536e3fdacadbd303ba6c Mon Sep 17 00:00:00 2001 From: giantim Date: Wed, 1 Apr 2020 11:23:22 +0900 Subject: [PATCH 28/29] =?UTF-8?q?refactor:=20=EC=88=98=EC=A0=95=ED=95=9C?= =?UTF-8?q?=20=ED=81=B4=EB=9E=98=EC=8A=A4=EC=97=90=20=EB=A7=9E=EA=B2=8C=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94=EB=93=9C=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 --- src/main/java/chess/domain/piece/Queen.java | 2 +- .../java/chess/domain/ChessRunnerTest.java | 21 ++++++++ .../chess/domain/board/BoardScoreTest.java | 28 ++++++++++ .../java/chess/domain/piece/BishopTest.java | 20 +++++++ .../java/chess/domain/piece/KingTest.java | 20 +++++++ .../java/chess/domain/piece/KnightTest.java | 20 +++++++ .../java/chess/domain/piece/PawnTest.java | 54 +++++++++++++++++++ .../java/chess/domain/piece/PieceTest.java | 5 ++ .../java/chess/domain/piece/QueenTest.java | 22 ++++++++ .../java/chess/domain/piece/RookTest.java | 20 +++++++ 10 files changed, 211 insertions(+), 1 deletion(-) create mode 100644 src/test/java/chess/domain/board/BoardScoreTest.java create mode 100644 src/test/java/chess/domain/piece/BishopTest.java create mode 100644 src/test/java/chess/domain/piece/KingTest.java create mode 100644 src/test/java/chess/domain/piece/KnightTest.java create mode 100644 src/test/java/chess/domain/piece/PawnTest.java create mode 100644 src/test/java/chess/domain/piece/QueenTest.java create mode 100644 src/test/java/chess/domain/piece/RookTest.java diff --git a/src/main/java/chess/domain/piece/Queen.java b/src/main/java/chess/domain/piece/Queen.java index c7379c01f75..ca246843c48 100644 --- a/src/main/java/chess/domain/piece/Queen.java +++ b/src/main/java/chess/domain/piece/Queen.java @@ -10,6 +10,6 @@ public Queen(PieceType pieceType, Team team) { @Override public boolean movable(Position source, Position target) { return new Rook(this.pieceType, this.team).movable(source, target) - && new Bishop(this.pieceType, this.team).movable(source, target); + || new Bishop(this.pieceType, this.team).movable(source, target); } } diff --git a/src/test/java/chess/domain/ChessRunnerTest.java b/src/test/java/chess/domain/ChessRunnerTest.java index e311062b9ee..2bc1178c4c6 100644 --- a/src/test/java/chess/domain/ChessRunnerTest.java +++ b/src/test/java/chess/domain/ChessRunnerTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; class ChessRunnerTest { @@ -53,4 +54,24 @@ void validateTarget() { .isInstanceOf(IllegalArgumentException.class) .hasMessage("목적지가 잘못되었습니다."); } + + @DisplayName("점수 계산 테스트") + @Test + void calculateScoreTest() { + assertThat(chessRunner.calculateScore()).isEqualTo(38d); + } + + @DisplayName("게임이 종료되었는지 검사") + @Test + void isEndChessTest() { + assertThat(chessRunner.isEndChess()).isFalse(); + } + + @DisplayName("게임이 종료되지 않았을 때 승자를 출력 시 예외 출력") + @Test + void getWinnerTest() { + assertThatThrownBy(() -> { + chessRunner.getWinner(); + }).isInstanceOf(AssertionError.class); + } } \ No newline at end of file diff --git a/src/test/java/chess/domain/board/BoardScoreTest.java b/src/test/java/chess/domain/board/BoardScoreTest.java new file mode 100644 index 00000000000..f7528351431 --- /dev/null +++ b/src/test/java/chess/domain/board/BoardScoreTest.java @@ -0,0 +1,28 @@ +package chess.domain.board; + +import chess.domain.piece.Pawn; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceType; +import chess.domain.piece.Team; +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.*; + +public class BoardScoreTest { + @DisplayName("같은 파일에 폰이 있을 때 점수 계산") + @Test + void pawnStrategyTest() { + List> sameFilePawns = new ArrayList<>(Arrays.asList( + new AbstractMap.SimpleEntry<>(Position.of("a3"), new Pawn(PieceType.PAWN, Team.WHITE)), + new AbstractMap.SimpleEntry<>(Position.of("a4"), new Pawn(PieceType.PAWN, Team.WHITE)), + new AbstractMap.SimpleEntry<>(Position.of("a5"), new Pawn(PieceType.PAWN, Team.WHITE)) + )); + + BoardScore boardScore = new BoardScore(10d); + + Assertions.assertThat(boardScore.pawnStrategy(sameFilePawns).getBoardScore()).isEqualTo(8.5); + } +} diff --git a/src/test/java/chess/domain/piece/BishopTest.java b/src/test/java/chess/domain/piece/BishopTest.java new file mode 100644 index 00000000000..e063194bd80 --- /dev/null +++ b/src/test/java/chess/domain/piece/BishopTest.java @@ -0,0 +1,20 @@ +package chess.domain.piece; + +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class BishopTest { + @DisplayName("비숍이 이동 가능한 곳인지 검사") + @Test + void movableTest() { + Piece bishop = new Bishop(PieceType.BISHOP, Team.WHITE); + Position source = Position.of("d4"); + Position movableTarget = Position.of("f6"); + Position nonMovableTarget = Position.of("d5"); + + Assertions.assertThat(bishop.movable(source, movableTarget)).isTrue(); + Assertions.assertThat(bishop.movable(source, nonMovableTarget)).isFalse(); + } +} diff --git a/src/test/java/chess/domain/piece/KingTest.java b/src/test/java/chess/domain/piece/KingTest.java new file mode 100644 index 00000000000..f621c911470 --- /dev/null +++ b/src/test/java/chess/domain/piece/KingTest.java @@ -0,0 +1,20 @@ +package chess.domain.piece; + +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class KingTest { + @DisplayName("킹이 이동 가능한 곳인지 검사") + @Test + void movableTest() { + Piece king = new King(PieceType.KING, Team.BLACK); + Position source = Position.of("d4"); + Position movableTarget = Position.of("d5"); + Position nonMovableTarget = Position.of("c7"); + + Assertions.assertThat(king.movable(source, movableTarget)).isTrue(); + Assertions.assertThat(king.movable(source, nonMovableTarget)).isFalse(); + } +} diff --git a/src/test/java/chess/domain/piece/KnightTest.java b/src/test/java/chess/domain/piece/KnightTest.java new file mode 100644 index 00000000000..24ac2b7bd85 --- /dev/null +++ b/src/test/java/chess/domain/piece/KnightTest.java @@ -0,0 +1,20 @@ +package chess.domain.piece; + +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class KnightTest { + @DisplayName("나이트가 이동 가능한 곳인지 검사") + @Test + void movableTest() { + Piece knight = new Knight(PieceType.KNIGHT, Team.BLACK); + Position source = Position.of("d4"); + Position movableTarget = Position.of("c6"); + Position nonMovableTarget = Position.of("c7"); + + Assertions.assertThat(knight.movable(source, movableTarget)).isTrue(); + Assertions.assertThat(knight.movable(source, nonMovableTarget)).isFalse(); + } +} diff --git a/src/test/java/chess/domain/piece/PawnTest.java b/src/test/java/chess/domain/piece/PawnTest.java new file mode 100644 index 00000000000..42222b383f4 --- /dev/null +++ b/src/test/java/chess/domain/piece/PawnTest.java @@ -0,0 +1,54 @@ +package chess.domain.piece; + +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class PawnTest { + @DisplayName("흰색 폰이 이동 가능한 곳인지 검사") + @Test + void whitePawnMovableTest() { + Piece whitePawn = new Pawn(PieceType.PAWN, Team.WHITE); + Position initialSource = Position.of("a2"); + Position directOne = Position.of("a3"); + Position directTwo = Position.of("a4"); + Position nonMovableInitial = Position.of("a5"); + + Position nonInitialSource = Position.of("b3"); + Position diagonalTarget = Position.of("c4"); + Position directTarget = Position.of("b4"); + Position nonMovableTarget = Position.of("b5"); + + Assertions.assertThat(whitePawn.movable(initialSource, directOne)).isTrue(); + Assertions.assertThat(whitePawn.movable(initialSource, directTwo)).isTrue(); + Assertions.assertThat(whitePawn.movable(initialSource, nonMovableInitial)).isFalse(); + + Assertions.assertThat(whitePawn.movable(nonInitialSource, diagonalTarget)).isTrue(); + Assertions.assertThat(whitePawn.movable(nonInitialSource, directTarget)).isTrue(); + Assertions.assertThat(whitePawn.movable(nonInitialSource, nonMovableTarget)).isFalse(); + } + + @DisplayName("검은색 폰이 이동 가능한 곳인지 검사") + @Test + void blackPawnMovableTest() { + Piece blackPawn = new Pawn(PieceType.PAWN, Team.BLACK); + Position initialSource = Position.of("a7"); + Position directOne = Position.of("a6"); + Position directTwo = Position.of("a5"); + Position nonMovableInitial = Position.of("a4"); + + Position nonInitialSource = Position.of("b6"); + Position diagonalTarget = Position.of("c5"); + Position directTarget = Position.of("b5"); + Position nonMovableTarget = Position.of("b4"); + + Assertions.assertThat(blackPawn.movable(initialSource, directOne)).isTrue(); + Assertions.assertThat(blackPawn.movable(initialSource, directTwo)).isTrue(); + Assertions.assertThat(blackPawn.movable(initialSource, nonMovableInitial)).isFalse(); + + Assertions.assertThat(blackPawn.movable(nonInitialSource, diagonalTarget)).isTrue(); + Assertions.assertThat(blackPawn.movable(nonInitialSource, directTarget)).isTrue(); + Assertions.assertThat(blackPawn.movable(nonInitialSource, nonMovableTarget)).isFalse(); + } +} diff --git a/src/test/java/chess/domain/piece/PieceTest.java b/src/test/java/chess/domain/piece/PieceTest.java index 926051f7da8..5b5268a57b0 100644 --- a/src/test/java/chess/domain/piece/PieceTest.java +++ b/src/test/java/chess/domain/piece/PieceTest.java @@ -11,6 +11,7 @@ class PieceTest { void toSymbol() { Piece whitePiece = new Bishop(PieceType.BISHOP, Team.WHITE); Piece blackPiece = new Bishop(PieceType.BISHOP, Team.BLACK); + assertThat(whitePiece.toSymbol()).isEqualTo("b"); assertThat(blackPiece.toSymbol()).isEqualTo("B"); } @@ -20,7 +21,10 @@ void toSymbol() { void isEnemy() { Piece whitePiece = new Knight(PieceType.KNIGHT, Team.WHITE); Piece blackPiece = new Knight(PieceType.KNIGHT, Team.BLACK); + assertThat(whitePiece.isEnemy(blackPiece)).isTrue(); + assertThat(whitePiece.isEnemy(Team.BLACK)).isTrue(); + assertThat(blackPiece.isEnemy(Team.WHITE)).isTrue(); } @DisplayName("피스가 흰 팀의 킹인지 테스트") @@ -28,6 +32,7 @@ void isEnemy() { void isWhiteKing() { Piece whiteKing = new King(PieceType.KING, Team.WHITE); Piece blackBishop = new Bishop(PieceType.BISHOP, Team.BLACK); + assertThat(whiteKing.isWhiteKing()).isTrue(); assertThat(blackBishop.isWhiteKing()).isFalse(); } diff --git a/src/test/java/chess/domain/piece/QueenTest.java b/src/test/java/chess/domain/piece/QueenTest.java new file mode 100644 index 00000000000..59a70e90cc1 --- /dev/null +++ b/src/test/java/chess/domain/piece/QueenTest.java @@ -0,0 +1,22 @@ +package chess.domain.piece; + +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class QueenTest { + @DisplayName("퀸이 이동 가능한 곳인지 검사") + @Test + void movableTest() { + Piece queen = new Queen(PieceType.QUEEN, Team.BLACK); + Position source = Position.of("d4"); + Position diagonalTarget = Position.of("g7"); + Position directTarget = Position.of("d8"); + Position nonMovableTarget = Position.of("c7"); + + Assertions.assertThat(queen.movable(source, diagonalTarget)).isTrue(); + Assertions.assertThat(queen.movable(source, directTarget)).isTrue(); + Assertions.assertThat(queen.movable(source, nonMovableTarget)).isFalse(); + } +} diff --git a/src/test/java/chess/domain/piece/RookTest.java b/src/test/java/chess/domain/piece/RookTest.java new file mode 100644 index 00000000000..7826eecfbee --- /dev/null +++ b/src/test/java/chess/domain/piece/RookTest.java @@ -0,0 +1,20 @@ +package chess.domain.piece; + +import chess.domain.position.Position; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class RookTest { + @DisplayName("룩이 이동 가능한 곳인지 검사") + @Test + void movableTest() { + Piece rook = new Rook(PieceType.ROOK, Team.BLACK); + Position source = Position.of("d4"); + Position movableTarget = Position.of("d7"); + Position nonMovableTarget = Position.of("c7"); + + Assertions.assertThat(rook.movable(source, movableTarget)).isTrue(); + Assertions.assertThat(rook.movable(source, nonMovableTarget)).isFalse(); + } +} From 9f2711eedad07bb45663713b791f1e793d82cf8d Mon Sep 17 00:00:00 2001 From: giantim Date: Fri, 3 Apr 2020 13:40:58 +0900 Subject: [PATCH 29/29] =?UTF-8?q?refactor:=20=EC=9D=B4=EB=8F=99=EC=9D=84?= =?UTF-8?q?=20=EB=AA=BB=ED=95=98=EB=8A=94=20=EB=B2=84=EA=B7=B8=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 --- .../chess/controller/ChessController.java | 11 ++++++++++- src/main/java/chess/domain/ChessRunner.java | 15 ++++++++++++--- src/main/java/chess/domain/board/Board.java | 9 ++++----- .../java/chess/domain/board/BoardTest.java | 19 +++++++++---------- 4 files changed, 35 insertions(+), 19 deletions(-) diff --git a/src/main/java/chess/controller/ChessController.java b/src/main/java/chess/controller/ChessController.java index f5bb64d8294..6cefa41bd88 100644 --- a/src/main/java/chess/controller/ChessController.java +++ b/src/main/java/chess/controller/ChessController.java @@ -13,7 +13,7 @@ public class ChessController { private static OutputView outputView = new ConsoleOutputView(); public static void start() { - Command command = Command.of(inputView.askChessRun()); + Command command = getCommand(); if (command.isStart()) { ChessRunner chessRunner = new ChessRunner(); GameController gameController = command.getGameController(); @@ -23,6 +23,15 @@ public static void start() { } } + private static Command getCommand() { + try { + return Command.of(inputView.askChessRun()); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return getCommand(); + } + } + private static void runChessGame(Command command, ChessRunner chessRunner) { do { command = validateExecute(command, chessRunner); diff --git a/src/main/java/chess/domain/ChessRunner.java b/src/main/java/chess/domain/ChessRunner.java index 4652a0e677b..a886c58ebfe 100644 --- a/src/main/java/chess/domain/ChessRunner.java +++ b/src/main/java/chess/domain/ChessRunner.java @@ -23,7 +23,7 @@ public ChessRunner() { public void update(String source, String target) { Position sourcePosition = Position.of(source); Position targetPosition = Position.of(target); - Piece sourcePiece = this.board.getPiece(sourcePosition); + Piece sourcePiece = getSourcePiece(sourcePosition); checkCorrectTurn(sourcePiece); checkUpdateBoard(sourcePosition, targetPosition, sourcePiece); @@ -32,6 +32,15 @@ public void update(String source, String target) { changeTeam(); } + private Piece getSourcePiece(Position source) { + Optional sourcePiece = this.board.getPiece(source); + if (!sourcePiece.isPresent()) { + throw new IllegalArgumentException("비어있는 위치를 선택했습니다."); + } + + return sourcePiece.get(); + } + private void checkCorrectTurn(Piece sourcePiece) { if (sourcePiece.isEnemy(this.currentTeam)) { throw new IllegalArgumentException("현재 차례가 아닙니다."); @@ -72,8 +81,8 @@ private boolean isEmptyPath(final Position sourcePosition, final Position target } private boolean isMovableTarget(final Piece sourcePiece, final Position targetPosition) { - Piece targetPiece = this.board.getPiece(targetPosition); - return sourcePiece.isEnemy(targetPiece); + Optional targetPiece = this.board.getPiece(targetPosition); + return targetPiece.map(sourcePiece::isEnemy).orElse(true); } private void updateBoard(Position sourcePosition, Position targetPosition) { diff --git a/src/main/java/chess/domain/board/Board.java b/src/main/java/chess/domain/board/Board.java index 13ef182755a..dd387f3ffb4 100644 --- a/src/main/java/chess/domain/board/Board.java +++ b/src/main/java/chess/domain/board/Board.java @@ -74,12 +74,11 @@ public boolean isEmpty(final Position position) { return !this.board.containsKey(position); } - public Piece getPiece(final Position position) { - if (!this.board.containsKey(position)) { - throw new IllegalArgumentException("비어있는 위치를 선택하였습니다."); + public Optional getPiece(final Position position) { + if (this.board.containsKey(position)) { + return Optional.of(this.board.get(position)); } - - return this.board.get(position); + return Optional.empty(); } public Map parse() { diff --git a/src/test/java/chess/domain/board/BoardTest.java b/src/test/java/chess/domain/board/BoardTest.java index c1cb9c4df07..9e9bfc6cf6c 100644 --- a/src/test/java/chess/domain/board/BoardTest.java +++ b/src/test/java/chess/domain/board/BoardTest.java @@ -20,9 +20,9 @@ void updateAtEmptyBoard() { board.updateBoard(source, target); Assertions.assertThatThrownBy(() -> { - board.getPiece(source); - }).isInstanceOf(IllegalArgumentException.class); - Assertions.assertThat(board.getPiece(target)).isInstanceOf(Piece.class); + board.getPiece(source).get(); + }).isInstanceOf(NoSuchElementException.class); + Assertions.assertThat(board.getPiece(target).get()).isInstanceOf(Piece.class); } @DisplayName("상대 편으로 말 이동") @@ -39,10 +39,9 @@ void updateAtEnemy() { board.updateBoard(source, target); Assertions.assertThatThrownBy(() -> { - board.getPiece(source); - }).isInstanceOf(IllegalArgumentException.class); - Assertions.assertThat(board.getPiece(target)).isNotNull(); - Assertions.assertThat(board.getPiece(target)).isInstanceOf(Piece.class); + board.getPiece(source).get(); + }).isInstanceOf(NoSuchElementException.class); + Assertions.assertThat(board.getPiece(target).get()).isInstanceOf(Piece.class); } @DisplayName("승자 팀을 판단") @@ -84,10 +83,10 @@ void isEmptyTest() { void getPieceTest() { Board board = new Board(); - Assertions.assertThat(board.getPiece(Position.of("a2"))).isInstanceOf(Piece.class); + Assertions.assertThat(board.getPiece(Position.of("a2")).get()).isInstanceOf(Piece.class); Assertions.assertThatThrownBy(() -> { - board.getPiece(Position.of("a3")); - }).isInstanceOf(IllegalArgumentException.class); + board.getPiece(Position.of("a3")).get(); + }).isInstanceOf(NoSuchElementException.class); } @DisplayName("같은 세로줄에 폰이 없을 때 점수 계산")