From 5002980a9147097937c7d1b0e70aa28f54618e2b Mon Sep 17 00:00:00 2001 From: aegis1920 Date: Tue, 28 Apr 2020 00:10:35 +0900 Subject: [PATCH] =?UTF-8?q?[=EB=B9=99=EB=B4=89]=20=EC=B2=B4=EC=8A=A4=20?= =?UTF-8?q?=EC=8A=A4=ED=94=84=EB=A7=81=20=EC=8B=A4=EC=8A=B5=202=EB=8B=A8?= =?UTF-8?q?=EA=B3=84=20=EC=A0=9C=EC=B6=9C=ED=95=A9=EB=8B=88=EB=8B=A4.=20(#?= =?UTF-8?q?91)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [디디] 체스 스프링 실습 1단계 제출합니다. (#12) * initial commit * fix : build.gradle mysql 의존성 추가 * refactor : 왕이 죽었을 때 게임이 종료 안되는 버그 수정 * refactor : 버튼으로 방에 입장할 수 있도록 함 * refactor : 방을 삭제하고 나서 새로고침해야 적용되던 문제 수정 * feat : 방에 입장하자마자 게임을 바로 불러오도록 하고 못 불러왔을 시 게임을 초기화하는 기능 추가, refactor : 불러왔을 때 현재 Turn이 나오지 않는 문제 수정 * refactor, style : tab 공백을 space로 변경, 익명 객체 람다식으로 수정 * feat : Spring room Controller 구현 - 방 제목 empty 에 대한 validation 추가 - default 요청시 바로 방 목록을 불러오도록 수정 * feat, refactor : Dto 생성 방식 수정, 게임 컨트롤러 구현 - 게임 초기화 기능 구현 Co-authored-by: aegis * [디디] 체스 - 스프링 실습 2단계 제출합니다. (#73) * refactor : 사용하지 않는 클래스 삭제 * refactor : 디폴트 생성자 접근제어자 수정 * refactor : 디폴트 생성자 접근제어자 수정 * refactor : 디폴트 생성자 접근제어자 수정 * refactor : Object 객체 타입 파라미터 반영하도록 수정 * refactor : 필드간 공백 추가 * refactor : 사용하지 않는 메서드 삭제 * refactor : 필드 접근제어자 추가 * style : 공백 추가 * feat : gameController init, movablePosition 구현 - todo : move시 에러 * feat : move 예외 처리 작업중 * refactor : spring MVC 구조에 맞게 refactor - GameController 예외 알맞게 처리 - DAO 클래스 Repository로 설정 - Service의 DAO를 bean으로 주입 * docs : README.md 추가 * test : domain test 메서드 추가 * refactor : 사용하지 않은 메서드 삭제 및 공백 수정 * refactor, fix : Spark Application과 Spring Application 이 모두 동작하도록 수정, 점수가 제대로 나오지 않는 버그 수정 * style : 공백 삭제 * refactor : move 메서드가 Post방식의 Json으로 요청을 받도록 수정 - front의 request uri 수정 - MoveManagerDTO 클래스로 request 매핑 * refactor : 불필요한 attribute 삭제 * refactor : move 메서드 리턴 타입 수정, 클래스명 수정 * refactor : 서비스 메서드 불필요한 동작 수정 Co-authored-by: aegis Co-authored-by: DD <48818566+fucct@users.noreply.github.com> --- .../wooteco/chess/SparkChessApplication.java | 41 ++- .../wooteco/chess/SpringChessApplication.java | 7 +- .../chess/controller/SparkGameController.java | 97 ----- .../chess/controller/SparkRoomController.java | 55 --- .../controller/SpringGameController.java | 58 ++- .../controller/SpringRoomController.java | 8 +- src/main/java/wooteco/chess/dao/GameDAO.java | 2 - src/main/java/wooteco/chess/dao/RoomDAO.java | 2 - .../java/wooteco/chess/dao/SparkGameDAO.java | 157 ++++++++ .../java/wooteco/chess/dao/SparkRoomDAO.java | 166 +++++++++ .../wooteco/chess/domain/GameManager.java | 2 - .../java/wooteco/chess/dto/GameStatusDTO.java | 19 + .../wooteco/chess/dto/MoveRequestDTO.java | 26 ++ .../wooteco/chess/dto/MoveResponseDTO.java | 38 ++ .../chess/{controller => dto}/RoomName.java | 2 +- ...GameService.java => SparkGameService.java} | 44 ++- .../chess/service/SparkRoomService.java | 31 ++ .../chess/service/SpringGameService.java | 85 +++++ ...oomService.java => SpringRoomService.java} | 9 +- .../sparkcontroller/SparkGameController.java | 97 +++++ .../sparkcontroller/SparkRoomController.java | 55 +++ src/main/resources/application.properties | 1 - src/main/resources/banner.txt | 9 + src/main/resources/logback-access.xml | 2 +- src/main/resources/static/css/index.css | 3 +- src/main/resources/templates/game.hbs | 42 ++- src/main/resources/templates/game.html | 339 ++++++++++++++++++ src/main/resources/templates/index.hbs | 6 +- src/main/resources/templates/index.html | 84 +++++ .../wooteco/chess/ChessApplicationTests.java | 6 +- .../java/wooteco/chess/domain/ColorTest.java | 12 +- .../wooteco/chess/domain/PieceScoreTest.java | 30 +- .../chess/domain/board/GameManagerTest.java | 202 +++++------ .../chess/domain/board/PositionTest.java | 38 +- .../chess/domain/piece/BishopTest.java | 80 ++--- .../wooteco/chess/domain/piece/BlankTest.java | 28 +- .../wooteco/chess/domain/piece/KingTest.java | 80 ++--- .../chess/domain/piece/KnightTest.java | 80 ++--- .../wooteco/chess/domain/piece/PawnTest.java | 116 +++--- .../wooteco/chess/domain/piece/PieceTest.java | 75 ++-- .../wooteco/chess/domain/piece/QueenTest.java | 82 ++--- .../wooteco/chess/domain/piece/RookTest.java | 80 ++--- .../wooteco/chess/util/JDBCConnectorTest.java | 12 +- 43 files changed, 1681 insertions(+), 727 deletions(-) delete mode 100644 src/main/java/wooteco/chess/controller/SparkGameController.java delete mode 100644 src/main/java/wooteco/chess/controller/SparkRoomController.java create mode 100644 src/main/java/wooteco/chess/dao/SparkGameDAO.java create mode 100644 src/main/java/wooteco/chess/dao/SparkRoomDAO.java create mode 100644 src/main/java/wooteco/chess/dto/GameStatusDTO.java create mode 100644 src/main/java/wooteco/chess/dto/MoveRequestDTO.java create mode 100644 src/main/java/wooteco/chess/dto/MoveResponseDTO.java rename src/main/java/wooteco/chess/{controller => dto}/RoomName.java (91%) rename src/main/java/wooteco/chess/service/{GameService.java => SparkGameService.java} (69%) create mode 100644 src/main/java/wooteco/chess/service/SparkRoomService.java create mode 100644 src/main/java/wooteco/chess/service/SpringGameService.java rename src/main/java/wooteco/chess/service/{RoomService.java => SpringRoomService.java} (76%) create mode 100644 src/main/java/wooteco/chess/sparkcontroller/SparkGameController.java create mode 100644 src/main/java/wooteco/chess/sparkcontroller/SparkRoomController.java create mode 100644 src/main/resources/banner.txt create mode 100644 src/main/resources/templates/game.html create mode 100644 src/main/resources/templates/index.html diff --git a/src/main/java/wooteco/chess/SparkChessApplication.java b/src/main/java/wooteco/chess/SparkChessApplication.java index feccbcf069..a5ed5c8780 100644 --- a/src/main/java/wooteco/chess/SparkChessApplication.java +++ b/src/main/java/wooteco/chess/SparkChessApplication.java @@ -1,12 +1,11 @@ package wooteco.chess; -import wooteco.chess.controller.SparkGameController; -import wooteco.chess.controller.SparkRoomController; import com.google.gson.Gson; import com.google.gson.JsonObject; +import wooteco.chess.sparkcontroller.SparkGameController; +import wooteco.chess.sparkcontroller.SparkRoomController; import static spark.Spark.*; -import static spark.Spark.exception; public class SparkChessApplication { public static void main(String[] args) { @@ -14,23 +13,23 @@ public static void main(String[] args) { staticFiles.location("/static"); externalStaticFileLocation("src/main/resources/templates"); -// get(SparkRoomController.BASIC_URL, SparkRoomController.getAllRoom); -// get(SparkRoomController.CREATE_ROOM_URL, SparkRoomController.createRoom); -// get(SparkRoomController.REMOVE_ROOM_URL, SparkRoomController.removeRoom); -// get(SparkRoomController.ENTER_ROOM_URL, SparkRoomController.enterRoom); -// -// get(SparkGameController.INIT_URL, SparkGameController::initGame); -// post(SparkGameController.MOVE_URL, SparkGameController::movePiece); -// get(SparkGameController.STATUS_URL, SparkGameController::showStatus); -// get(SparkGameController.LOAD_URL, SparkGameController::loadGame); -// get(SparkGameController.GET_URL, SparkGameController::getMovablePositions); -// -// exception(IllegalArgumentException.class, (e, req, res) -> { -// Gson gson = new Gson(); -// JsonObject object = new JsonObject(); -// -// object.addProperty("errorMessage", e.getMessage()); -// res.body(gson.toJson(object)); -// }); + get(SparkRoomController.BASIC_URL, SparkRoomController.getAllRoom); + get(SparkRoomController.CREATE_ROOM_URL, SparkRoomController.createRoom); + get(SparkRoomController.REMOVE_ROOM_URL, SparkRoomController.removeRoom); + get(SparkRoomController.ENTER_ROOM_URL, SparkRoomController.enterRoom); + + get(SparkGameController.INIT_URL, SparkGameController::initGame); + post(SparkGameController.MOVE_URL, SparkGameController::movePiece); + get(SparkGameController.STATUS_URL, SparkGameController::showStatus); + get(SparkGameController.LOAD_URL, SparkGameController::loadGame); + get(SparkGameController.GET_URL, SparkGameController::getMovablePositions); + + exception(IllegalArgumentException.class, (e, req, res) -> { + Gson gson = new Gson(); + JsonObject object = new JsonObject(); + + object.addProperty("errorMessage", e.getMessage()); + res.body(gson.toJson(object)); + }); } } diff --git a/src/main/java/wooteco/chess/SpringChessApplication.java b/src/main/java/wooteco/chess/SpringChessApplication.java index b23c24d0bd..2604f73ab2 100644 --- a/src/main/java/wooteco/chess/SpringChessApplication.java +++ b/src/main/java/wooteco/chess/SpringChessApplication.java @@ -6,8 +6,7 @@ @SpringBootApplication public class SpringChessApplication { - public static void main(String[] args) { - SpringApplication.run(SpringChessApplication.class, args); - } - + public static void main(String[] args) { + SpringApplication.run(SpringChessApplication.class, args); + } } diff --git a/src/main/java/wooteco/chess/controller/SparkGameController.java b/src/main/java/wooteco/chess/controller/SparkGameController.java deleted file mode 100644 index 479e42a625..0000000000 --- a/src/main/java/wooteco/chess/controller/SparkGameController.java +++ /dev/null @@ -1,97 +0,0 @@ -package wooteco.chess.controller; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import spark.Request; -import spark.Response; -import wooteco.chess.domain.Color; -import wooteco.chess.service.GameService; - -import java.sql.SQLException; - -public class SparkGameController { -// public static final String BASIC_URL = "/game"; -// public static final String MOVE_URL = BASIC_URL + "/move"; -// public static final String STATUS_URL = BASIC_URL + "/status"; -// public static final String INIT_URL = BASIC_URL + "/init"; -// public static final String LOAD_URL = BASIC_URL + "/load"; -// public static final String GET_URL = BASIC_URL + "/get"; -// -// public static String initGame(Request request, Response response) throws SQLException { -// GameService gameService = GameService.getInstance(); -// int roomId = Integer.parseInt(request.queryParams("roomId")); -// gameService.initialize(roomId); -// -// Gson gson = new Gson(); -// JsonObject object = new JsonObject(); -// String pieces = gson.toJson(gameService.getPiecesResponseDTO(roomId).getPieces()); -// String currentColor = gameService.getCurrentColor(roomId); -// -// object.addProperty("pieces", pieces); -// object.addProperty("currentColor", currentColor); -// -// return gson.toJson(object); -// } -// -// public static String movePiece(Request request, Response response) throws SQLException { -// GameService gameService = GameService.getInstance(); -// -// int roomId = Integer.parseInt(request.queryParams("roomId")); -// String sourcePosition = request.queryParams("sourcePosition"); -// String targetPosition = request.queryParams("targetPosition"); -// gameService.movePiece(roomId, sourcePosition, targetPosition); -// boolean kingDead = gameService.isKingDead(roomId); -// String currentColor = gameService.getCurrentColor(roomId); -// -// Gson gson = new Gson(); -// JsonObject object = new JsonObject(); -// String pieces = gson.toJson(gameService.getPiecesResponseDTO(roomId).getPieces()); -// -// object.addProperty("pieces", pieces); -// object.addProperty("kingDead", kingDead); -// object.addProperty("currentColor", currentColor); -// -// return gson.toJson(object); -// } -// -// public static String showStatus(Request request, Response response) throws SQLException { -// GameService gameService = GameService.getInstance(); -// int roomId = Integer.parseInt(request.queryParams("roomId")); -// -// double whiteScore = gameService.getScore(roomId, Color.WHITE); -// double blackScore = gameService.getScore(roomId, Color.BLACK); -// -// Gson gson = new Gson(); -// JsonObject object = new JsonObject(); -// -// object.addProperty("whiteScore", whiteScore); -// object.addProperty("blackScore", blackScore); -// -// return gson.toJson(object); -// } -// -// public static String loadGame(Request request, Response response) throws SQLException { -// GameService gameService = GameService.getInstance(); -// int roomId = Integer.parseInt(request.queryParams("roomId")); -// -// Gson gson = new Gson(); -// JsonObject object = new JsonObject(); -// String pieces = gson.toJson(gameService.getPiecesResponseDTO(roomId).getPieces()); -// String currentColor = gameService.getCurrentColor(roomId); -// -// object.addProperty("pieces", pieces); -// object.addProperty("currentColor", currentColor); -// -// return gson.toJson(object); -// } -// -// public static String getMovablePositions(final Request request, final Response response) throws SQLException { -// GameService gameService = GameService.getInstance(); -// int roomId = Integer.parseInt(request.queryParams("roomId")); -// String sourcePosition = request.queryParams("sourcePosition"); -// -// Gson gson = new Gson(); -// -// return gson.toJson(gameService.getMovablePositions(roomId, sourcePosition)); -// } -} diff --git a/src/main/java/wooteco/chess/controller/SparkRoomController.java b/src/main/java/wooteco/chess/controller/SparkRoomController.java deleted file mode 100644 index f07b77f56b..0000000000 --- a/src/main/java/wooteco/chess/controller/SparkRoomController.java +++ /dev/null @@ -1,55 +0,0 @@ -package wooteco.chess.controller; - -import wooteco.chess.domain.room.Room; -import wooteco.chess.service.RoomService; -import spark.Route; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static wooteco.chess.util.HandlebarsUtil.render; - -public class SparkRoomController { - public static final String BASIC_URL = "/rooms"; - public static final String ENTER_ROOM_URL = BASIC_URL + "/enter"; - public static final String CREATE_ROOM_URL = BASIC_URL + "/create"; - public static final String REMOVE_ROOM_URL = BASIC_URL + "/remove"; - -// public static Route getAllRoom = (request, response) -> { -// Map model = new HashMap<>(); -// -// RoomService roomService = RoomService.getInstance(); -// List rooms = roomService.findAllRoom(); -// model.put("rooms", rooms); -// -// return render(model, "index.hbs"); -// }; -// -// public static Route enterRoom = (request, response) -> { -// Map model = new HashMap<>(); -// model.put("roomId", request.queryParams("roomId")); -// -// return render(model, "game.hbs"); -// }; -// -// public static Route createRoom = (request, response) -> { -// RoomService roomService = RoomService.getInstance(); -// String param = request.queryParams("roomName"); -// roomService.addRoom(param); -// -// response.redirect("/rooms"); -// return null; -// }; -// -// public static Route removeRoom = (request, response) -> { -// RoomService roomService = RoomService.getInstance(); -// roomService.removeRoom(Integer.parseInt(request.queryParams("roomId"))); -// -// response.redirect("/rooms"); -// return null; -// }; -// -// private SparkRoomController() { -// } -} diff --git a/src/main/java/wooteco/chess/controller/SpringGameController.java b/src/main/java/wooteco/chess/controller/SpringGameController.java index 518341f451..ececae641c 100644 --- a/src/main/java/wooteco/chess/controller/SpringGameController.java +++ b/src/main/java/wooteco/chess/controller/SpringGameController.java @@ -1,69 +1,53 @@ package wooteco.chess.controller; -import com.google.gson.Gson; -import com.google.gson.JsonObject; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ui.Model; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import org.springframework.web.servlet.ModelAndView; -import spark.Request; -import spark.Response; import wooteco.chess.domain.Color; -import wooteco.chess.domain.GameManager; -import wooteco.chess.dto.GameManagerDTO; -import wooteco.chess.dto.MovablePositionDTO; -import wooteco.chess.dto.MovePositionDTO; -import wooteco.chess.service.GameService; +import wooteco.chess.dto.MoveResponseDTO; +import wooteco.chess.dto.GameStatusDTO; +import wooteco.chess.dto.MoveRequestDTO; +import wooteco.chess.service.SpringGameService; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.sql.SQLException; -import java.util.Collection; import java.util.List; -import java.util.Objects; @RestController @RequestMapping("/game") public class SpringGameController { - @Autowired - private GameService gameService; + private final SpringGameService gameService; + + public SpringGameController(final SpringGameService gameService) { + this.gameService = gameService; + } @GetMapping("/init") - public GameManagerDTO init(@RequestParam(value = "roomId") Integer roomId) throws SQLException { + public MoveResponseDTO init(@RequestParam Integer roomId) throws SQLException { return gameService.initialize(roomId); } @PostMapping("/move") - public GameManagerDTO move(HttpServletRequest request) throws SQLException { - int roomId = Integer.parseInt(request.getParameter("roomId")); - String sourcePosition = request.getParameter("sourcePosition"); - String targetPosition = request.getParameter("targetPosition"); - - GameManagerDTO gameManagerDTO = gameService.createDTO(roomId); + public ResponseEntity move(@RequestBody MoveRequestDTO requestDTO) throws SQLException { try { - gameService.movePiece(roomId, sourcePosition, targetPosition); - return gameService.createDTO(roomId); + return ResponseEntity.status(HttpStatus.OK).body(gameService.move(requestDTO)); } catch (IllegalArgumentException e) { - gameManagerDTO.setErrorMessage(e.getMessage()); - return gameManagerDTO; + MoveResponseDTO moveResponseDTO = gameService.createMoveResponseDTO(requestDTO.getRoomId()); + moveResponseDTO.setErrorMessage(e.getMessage()); + return ResponseEntity.status(HttpStatus.OK).body(moveResponseDTO); } } @GetMapping("/status") - public Model showStatus(@RequestParam Integer roomId, Model model) throws SQLException { - double whiteScore = gameService.getScore(roomId, Color.WHITE); - double blackScore = gameService.getScore(roomId, Color.BLACK); - - model.addAttribute("whiteScore", whiteScore); - model.addAttribute("blackScore", blackScore); - - return model; + public GameStatusDTO showStatus(@RequestParam Integer roomId) throws SQLException { + return new GameStatusDTO(gameService.getScore(roomId, Color.WHITE), gameService.getScore(roomId, Color.BLACK)); } @GetMapping("/load") - public GameManagerDTO load(@RequestParam Integer roomId) throws SQLException { - return gameService.createDTO(roomId); + public MoveResponseDTO load(@RequestParam Integer roomId) throws SQLException { + return gameService.createMoveResponseDTO(roomId); } @GetMapping("/get") diff --git a/src/main/java/wooteco/chess/controller/SpringRoomController.java b/src/main/java/wooteco/chess/controller/SpringRoomController.java index e9be82b4b2..f0a25bc602 100644 --- a/src/main/java/wooteco/chess/controller/SpringRoomController.java +++ b/src/main/java/wooteco/chess/controller/SpringRoomController.java @@ -1,6 +1,5 @@ package wooteco.chess.controller; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; @@ -8,7 +7,8 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import wooteco.chess.domain.room.Room; -import wooteco.chess.service.RoomService; +import wooteco.chess.dto.RoomName; +import wooteco.chess.service.SpringRoomService; import javax.validation.Valid; import java.sql.SQLException; @@ -18,9 +18,9 @@ @RequestMapping("/rooms") public class SpringRoomController { - private final RoomService roomService; + private final SpringRoomService roomService; - private SpringRoomController(final RoomService roomService) { + private SpringRoomController(final SpringRoomService roomService) { this.roomService = roomService; } diff --git a/src/main/java/wooteco/chess/dao/GameDAO.java b/src/main/java/wooteco/chess/dao/GameDAO.java index 39e0d69d2a..7b6dcd250b 100644 --- a/src/main/java/wooteco/chess/dao/GameDAO.java +++ b/src/main/java/wooteco/chess/dao/GameDAO.java @@ -7,8 +7,6 @@ import wooteco.chess.domain.piece.PieceMapper; import wooteco.chess.domain.piece.Pieces; -import java.sql.PreparedStatement; -import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/wooteco/chess/dao/RoomDAO.java b/src/main/java/wooteco/chess/dao/RoomDAO.java index ccba67c364..4377c14b7c 100644 --- a/src/main/java/wooteco/chess/dao/RoomDAO.java +++ b/src/main/java/wooteco/chess/dao/RoomDAO.java @@ -4,8 +4,6 @@ import wooteco.chess.domain.Color; import wooteco.chess.domain.room.Room; -import java.sql.PreparedStatement; -import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/wooteco/chess/dao/SparkGameDAO.java b/src/main/java/wooteco/chess/dao/SparkGameDAO.java new file mode 100644 index 0000000000..75b5499c9d --- /dev/null +++ b/src/main/java/wooteco/chess/dao/SparkGameDAO.java @@ -0,0 +1,157 @@ +package wooteco.chess.dao; + +import wooteco.chess.domain.board.Position; +import wooteco.chess.domain.piece.Blank; +import wooteco.chess.domain.piece.Piece; +import wooteco.chess.domain.piece.PieceMapper; +import wooteco.chess.domain.piece.Pieces; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; + +public class SparkGameDAO { + private static final SparkGameDAO GAME_DAO = new SparkGameDAO(); + + public static SparkGameDAO getInstance() { + return GAME_DAO; + } + + public void removeAllPiecesById(int roomId) throws SQLException { + String query = "DELETE FROM board WHERE room_id = ?"; + + PreparedStatementSetter pss = new PreparedStatementSetter() { + @Override + public void setParameters(final PreparedStatement pstmt) throws SQLException { + pstmt.setInt(1, roomId); + } + }; + + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + jdbcTemplate.executeUpdate(query, pss); + + } + + public void addAllPiecesById(int roomId, Pieces pieces) throws SQLException { + String query = "INSERT INTO board(room_id, piece_name, piece_position, piece_color) VALUES (?, ?, ?, ?)"; + + PreparedStatementSetter pss = new PreparedStatementSetter() { + @Override + public void setParameters(final PreparedStatement pstmt) throws SQLException { + for (Position position : pieces.getPieces().keySet()) { + Piece piece = pieces.getPieceByPosition(position); + + pstmt.setInt(1, roomId); + pstmt.setString(2, piece.getSymbol()); + pstmt.setString(3, position.getPosition()); + pstmt.setString(4, piece.getColor().name()); + pstmt.addBatch(); + } + } + }; + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + jdbcTemplate.executeBatch(query, pss); + } + + public void updatePieceByPosition(String currentPosition, String nextPosition) throws SQLException { + String query = "UPDATE board SET piece_position = ? WHERE piece_position = ?"; + + PreparedStatementSetter pss = new PreparedStatementSetter() { + @Override + public void setParameters(final PreparedStatement pstmt) throws SQLException { + pstmt.setString(1, nextPosition); + pstmt.setString(2, currentPosition); + } + }; + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + jdbcTemplate.executeUpdate(query, pss); + + } + + public void deletePieceByPosition(String position) throws SQLException { + String query = "DELETE FROM board WHERE piece_position = ?"; + + PreparedStatementSetter pss = new PreparedStatementSetter() { + @Override + public void setParameters(final PreparedStatement pstmt) throws SQLException { + pstmt.setString(1, position); + } + }; + + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + jdbcTemplate.executeUpdate(query, pss); + } + + public void addPieceByPosition(int roomId, Position position, Piece piece) throws SQLException { + String query = "INSERT INTO board(room_id, piece_name, piece_position, piece_color) VALUES (?, ?, ?, ?)"; + + PreparedStatementSetter pss = new PreparedStatementSetter() { + @Override + public void setParameters(final PreparedStatement pstmt) throws SQLException { + pstmt.setInt(1, roomId); + pstmt.setString(2, piece.getSymbol()); + pstmt.setString(3, position.getPosition()); + pstmt.setString(4, piece.getColor().name()); + } + }; + + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + jdbcTemplate.executeUpdate(query, pss); + } + + public Piece findPieceByPosition(String position) throws SQLException { + String query = "SELECT piece_name FROM board WHERE piece_position = ?"; + + PreparedStatementSetter pss = new PreparedStatementSetter() { + @Override + public void setParameters(final PreparedStatement pstmt) throws SQLException { + pstmt.setString(1, position); + } + }; + + RowMapper rm = new RowMapper() { + @Override + public Object mapRow(final ResultSet rs) throws SQLException { + if (!rs.next()) { + return Blank.getInstance(); + } + return PieceMapper.getInstance().findDBPiece(rs.getString("piece_name")); + } + }; + + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + return (Piece) jdbcTemplate.executeQuery(query, pss, rm); + } + + public Map findAllPiecesById(int roomId) throws SQLException { + String query = "SELECT piece_name, piece_position, piece_color FROM board WHERE room_id = ?"; + + PreparedStatementSetter pss = new PreparedStatementSetter() { + @Override + public void setParameters(final PreparedStatement pstmt) throws SQLException { + pstmt.setInt(1, roomId); + } + }; + + RowMapper rm = new RowMapper() { + @Override + public Object mapRow(final ResultSet rs) throws SQLException { + Map pieces = new HashMap<>(); + + while (rs.next()) { + String name = rs.getString("piece_name"); + String position = rs.getString("piece_position"); + pieces.put(Position.of(position), PieceMapper.getInstance().findDBPiece(name)); + } + + return pieces; + } + }; + + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + + return (Map) jdbcTemplate.executeQuery(query, pss, rm); + } +} diff --git a/src/main/java/wooteco/chess/dao/SparkRoomDAO.java b/src/main/java/wooteco/chess/dao/SparkRoomDAO.java new file mode 100644 index 0000000000..887cd16a97 --- /dev/null +++ b/src/main/java/wooteco/chess/dao/SparkRoomDAO.java @@ -0,0 +1,166 @@ +package wooteco.chess.dao; + +import wooteco.chess.domain.Color; +import wooteco.chess.domain.room.Room; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public class SparkRoomDAO { + private static final SparkRoomDAO ROOM_DAO = new SparkRoomDAO(); + + public static SparkRoomDAO getInstance() { + return ROOM_DAO; + } + + public void addRoom(String roomName, String roomColor) throws SQLException { + String query = "INSERT INTO room(room_name, room_color) VALUES (?, ?)"; + + PreparedStatementSetter pss = new PreparedStatementSetter() { + @Override + public void setParameters(final PreparedStatement pstmt) throws SQLException { + pstmt.setString(1, roomName); + pstmt.setString(2, roomColor); + } + }; + + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + jdbcTemplate.executeUpdate(query, pss); + } + + public void removeRoomById(int roomId) throws SQLException { + String query = "DELETE FROM room WHERE room_id = ?"; + + PreparedStatementSetter pss = new PreparedStatementSetter() { + @Override + public void setParameters(final PreparedStatement pstmt) throws SQLException { + pstmt.setInt(1, roomId); + } + }; + + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + jdbcTemplate.executeUpdate(query, pss); + } + + public void updateRoomColorById(int roomId, Color roomColor) throws SQLException { + String query = "UPDATE room SET room_color = ? WHERE room_id = ?"; + + PreparedStatementSetter pss = new PreparedStatementSetter() { + @Override + public void setParameters(final PreparedStatement pstmt) throws SQLException { + pstmt.setString(1, roomColor.name()); + pstmt.setInt(2, roomId); + } + }; + + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + jdbcTemplate.executeUpdate(query, pss); + } + + public Room findRoomById(int roomId) throws SQLException { + String query = "SELECT room_id, room_name, room_color FROM room WHERE room_id = ?"; + + PreparedStatementSetter pss = new PreparedStatementSetter() { + @Override + public void setParameters(final PreparedStatement pstmt) throws SQLException { + pstmt.setInt(1, roomId); + } + }; + + RowMapper rm = new RowMapper() { + @Override + public Object mapRow(final ResultSet rs) throws SQLException { + if (!rs.next()) { + return null; + } + return new Room( + rs.getInt("room_id"), + rs.getString("room_name"), + rs.getString("room_color") + ); + } + }; + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + return (Room) jdbcTemplate.executeQuery(query, pss, rm); + } + + public int findRoomIdByRoomName(String roomName) throws SQLException { + String query = "SELECT room_id FROM room WHERE room_name = ?"; + + PreparedStatementSetter pss = new PreparedStatementSetter() { + @Override + public void setParameters(final PreparedStatement pstmt) throws SQLException { + pstmt.setString(1, roomName); + } + }; + + RowMapper rm = new RowMapper() { + @Override + public Object mapRow(final ResultSet rs) throws SQLException { + if (!rs.next()) { + return 0; + } + + return rs.getInt("room_id"); + } + }; + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + return (int) jdbcTemplate.executeQuery(query, pss, rm); + } + + public List findAllRoom() throws SQLException { + String query = "SELECT room_id, room_name, room_color FROM room"; + + PreparedStatementSetter pss = new PreparedStatementSetter() { + @Override + public void setParameters(final PreparedStatement pstmt) throws SQLException { + + } + }; + + RowMapper rm = new RowMapper() { + @Override + public Object mapRow(final ResultSet rs) throws SQLException { + List rooms = new ArrayList<>(); + + while (rs.next()) { + int roomId = rs.getInt("room_id"); + String roomName = rs.getString("room_name"); + String roomColor = rs.getString("room_color"); + + rooms.add(new Room(roomId, roomName, roomColor)); + } + return rooms; + } + }; + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + return (List) jdbcTemplate.executeQuery(query, pss, rm); + } + + public Color findRoomColorById(int roomId) throws SQLException { + String query = "SELECT room_color FROM room WHERE room_id = ?"; + + PreparedStatementSetter pss = new PreparedStatementSetter() { + @Override + public void setParameters(final PreparedStatement pstmt) throws SQLException { + pstmt.setInt(1, roomId); + } + }; + + RowMapper rm = new RowMapper() { + @Override + public Object mapRow(final ResultSet rs) throws SQLException { + if (!rs.next()) { + return null; + } + return Color.valueOf(rs.getString("room_color")); + } + }; + + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + return (Color) jdbcTemplate.executeQuery(query, pss, rm); + } +} diff --git a/src/main/java/wooteco/chess/domain/GameManager.java b/src/main/java/wooteco/chess/domain/GameManager.java index 5fb579c0f7..94bbe0b5e8 100644 --- a/src/main/java/wooteco/chess/domain/GameManager.java +++ b/src/main/java/wooteco/chess/domain/GameManager.java @@ -19,9 +19,7 @@ public GameManager(Pieces pieces, Color currentColor) { public void moveFromTo(Position sourcePosition, Position targetPosition) { validateOtherPieceSourcePosition(sourcePosition); validateSameColorTargetPosition(targetPosition); - movePiece(sourcePosition, targetPosition); - nextTurn(); } diff --git a/src/main/java/wooteco/chess/dto/GameStatusDTO.java b/src/main/java/wooteco/chess/dto/GameStatusDTO.java new file mode 100644 index 0000000000..18774c5cda --- /dev/null +++ b/src/main/java/wooteco/chess/dto/GameStatusDTO.java @@ -0,0 +1,19 @@ +package wooteco.chess.dto; + +public class GameStatusDTO { + private final double whiteScore; + private final double blackScore; + + public GameStatusDTO(final double whiteScore, final double blackScore) { + this.whiteScore = whiteScore; + this.blackScore = blackScore; + } + + public double getWhiteScore() { + return whiteScore; + } + + public double getBlackScore() { + return blackScore; + } +} diff --git a/src/main/java/wooteco/chess/dto/MoveRequestDTO.java b/src/main/java/wooteco/chess/dto/MoveRequestDTO.java new file mode 100644 index 0000000000..a796d3487b --- /dev/null +++ b/src/main/java/wooteco/chess/dto/MoveRequestDTO.java @@ -0,0 +1,26 @@ +package wooteco.chess.dto; + +public class MoveRequestDTO { + + private Integer roomId; + private String sourcePosition; + private String targetPosition; + + public MoveRequestDTO(final Integer roomId, final String sourcePosition, final String targetPosition) { + this.roomId = roomId; + this.sourcePosition = sourcePosition; + this.targetPosition = targetPosition; + } + + public Integer getRoomId() { + return roomId; + } + + public String getSourcePosition() { + return sourcePosition; + } + + public String getTargetPosition() { + return targetPosition; + } +} diff --git a/src/main/java/wooteco/chess/dto/MoveResponseDTO.java b/src/main/java/wooteco/chess/dto/MoveResponseDTO.java new file mode 100644 index 0000000000..bca29fa903 --- /dev/null +++ b/src/main/java/wooteco/chess/dto/MoveResponseDTO.java @@ -0,0 +1,38 @@ +package wooteco.chess.dto; + +import wooteco.chess.domain.Color; + +import java.util.List; + +public class MoveResponseDTO { + private final List pieces; + private final Color currentColor; + private final boolean kingDead; + private String errorMessage; + + public MoveResponseDTO(final List pieces, final Color currentColor, final boolean kingDead) { + this.pieces = pieces; + this.currentColor = currentColor; + this.kingDead = kingDead; + } + + public List getPieces() { + return pieces; + } + + public Color getCurrentColor() { + return currentColor; + } + + public boolean isKingDead() { + return kingDead; + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(final String errorMessage) { + this.errorMessage = errorMessage; + } +} diff --git a/src/main/java/wooteco/chess/controller/RoomName.java b/src/main/java/wooteco/chess/dto/RoomName.java similarity index 91% rename from src/main/java/wooteco/chess/controller/RoomName.java rename to src/main/java/wooteco/chess/dto/RoomName.java index 1a1343c5fb..8876eb61ef 100644 --- a/src/main/java/wooteco/chess/controller/RoomName.java +++ b/src/main/java/wooteco/chess/dto/RoomName.java @@ -1,4 +1,4 @@ -package wooteco.chess.controller; +package wooteco.chess.dto; import javax.validation.constraints.NotEmpty; diff --git a/src/main/java/wooteco/chess/service/GameService.java b/src/main/java/wooteco/chess/service/SparkGameService.java similarity index 69% rename from src/main/java/wooteco/chess/service/GameService.java rename to src/main/java/wooteco/chess/service/SparkGameService.java index 862de2aecd..d3a5907c52 100644 --- a/src/main/java/wooteco/chess/service/GameService.java +++ b/src/main/java/wooteco/chess/service/SparkGameService.java @@ -1,40 +1,42 @@ package wooteco.chess.service; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import wooteco.chess.dao.GameDAO; -import wooteco.chess.dao.RoomDAO; +import wooteco.chess.dao.SparkGameDAO; +import wooteco.chess.dao.SparkRoomDAO; import wooteco.chess.domain.Color; import wooteco.chess.domain.GameManager; import wooteco.chess.domain.PieceScore; import wooteco.chess.domain.board.Position; import wooteco.chess.domain.piece.Pieces; -import wooteco.chess.dto.GameManagerDTO; import wooteco.chess.dto.PiecesResponseDTO; import java.sql.SQLException; import java.util.List; -@Service -public class GameService { +public class SparkGameService { + private static final SparkGameService GAME_SERVICE = new SparkGameService(); - @Autowired - private GameDAO gameDAO; + private SparkGameService() { + } + + public static SparkGameService getInstance() { + return GAME_SERVICE; + } - @Autowired - private RoomDAO roomDAO; + public void initialize(int roomId) throws SQLException { + SparkGameDAO gameDAO = SparkGameDAO.getInstance(); + SparkRoomDAO roomDAO = SparkRoomDAO.getInstance(); - public GameManagerDTO initialize(int roomId) throws SQLException { roomDAO.updateRoomColorById(roomId, Color.WHITE); Pieces pieces = new Pieces(Pieces.initPieces()); gameDAO.addAllPiecesById(roomId, pieces); - return new GameManagerDTO(new PiecesResponseDTO(pieces).getPieces(), Color.WHITE, false); } public void movePiece(int roomId, String sourcePosition, String targetPosition) throws SQLException { + SparkGameDAO gameDAO = SparkGameDAO.getInstance(); + SparkRoomDAO roomDAO = SparkRoomDAO.getInstance(); + Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); GameManager gameManager = new GameManager(pieces, roomDAO.findRoomColorById(roomId)); - gameManager.validateEndGame(); gameManager.moveFromTo(Position.of(sourcePosition), Position.of(targetPosition)); roomDAO.updateRoomColorById(roomId, gameManager.getCurrentColor()); @@ -43,6 +45,7 @@ public void movePiece(int roomId, String sourcePosition, String targetPosition) } public double getScore(int roomId, Color color) throws SQLException { + SparkGameDAO gameDAO = SparkGameDAO.getInstance(); Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); GameManager gameManager = new GameManager(pieces, color); @@ -50,29 +53,32 @@ public double getScore(int roomId, Color color) throws SQLException { } public PiecesResponseDTO getPiecesResponseDTO(int roomId) throws SQLException { + SparkGameDAO gameDAO = SparkGameDAO.getInstance(); Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); return new PiecesResponseDTO(pieces); } public boolean isKingDead(final int roomId) throws SQLException { + SparkGameDAO gameDAO = SparkGameDAO.getInstance(); + SparkRoomDAO roomDAO = SparkRoomDAO.getInstance(); + Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); GameManager gameManager = new GameManager(pieces, roomDAO.findRoomColorById(roomId)); return gameManager.isKingDead(); } public String getCurrentColor(final int roomId) throws SQLException { + SparkRoomDAO roomDAO = SparkRoomDAO.getInstance(); return roomDAO.findRoomColorById(roomId).name(); } public List getMovablePositions(final int roomId, final String sourcePosition) throws SQLException { + SparkGameDAO gameDAO = SparkGameDAO.getInstance(); + SparkRoomDAO roomDAO = SparkRoomDAO.getInstance(); + Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); GameManager gameManager = new GameManager(pieces, roomDAO.findRoomColorById(roomId)); return gameManager.getMovablePositions(Position.of(sourcePosition)); } - - public GameManagerDTO createDTO(final int roomId) throws SQLException { - return new GameManagerDTO(getPiecesResponseDTO(roomId).getPieces(), - Color.valueOf(getCurrentColor(roomId)), isKingDead(roomId)); - } } diff --git a/src/main/java/wooteco/chess/service/SparkRoomService.java b/src/main/java/wooteco/chess/service/SparkRoomService.java new file mode 100644 index 0000000000..c2209a111f --- /dev/null +++ b/src/main/java/wooteco/chess/service/SparkRoomService.java @@ -0,0 +1,31 @@ +package wooteco.chess.service; + +import wooteco.chess.dao.SparkRoomDAO; +import wooteco.chess.domain.room.Room; + +import java.sql.SQLException; +import java.util.List; + +public class SparkRoomService { + private static final SparkRoomService ROOM_SERVICE = new SparkRoomService(); + + public static SparkRoomService getInstance() { + return ROOM_SERVICE; + } + + public void addRoom(String roomName) throws SQLException { + SparkRoomDAO roomDAO = SparkRoomDAO.getInstance(); + roomDAO.addRoom(roomName, "WHITE"); + } + + public void removeRoom(int roomId) throws SQLException { + SparkRoomDAO roomDAO = SparkRoomDAO.getInstance(); + roomDAO.removeRoomById(roomId); + } + + public List findAllRoom() throws SQLException { + SparkRoomDAO roomDAO = SparkRoomDAO.getInstance(); + List rooms = roomDAO.findAllRoom(); + return rooms; + } +} diff --git a/src/main/java/wooteco/chess/service/SpringGameService.java b/src/main/java/wooteco/chess/service/SpringGameService.java new file mode 100644 index 0000000000..4fd36b54df --- /dev/null +++ b/src/main/java/wooteco/chess/service/SpringGameService.java @@ -0,0 +1,85 @@ +package wooteco.chess.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import wooteco.chess.dao.GameDAO; +import wooteco.chess.dao.RoomDAO; +import wooteco.chess.domain.Color; +import wooteco.chess.domain.GameManager; +import wooteco.chess.domain.PieceScore; +import wooteco.chess.domain.board.Position; +import wooteco.chess.domain.piece.Pieces; +import wooteco.chess.dto.MoveRequestDTO; +import wooteco.chess.dto.MoveResponseDTO; +import wooteco.chess.dto.PiecesResponseDTO; + +import java.sql.SQLException; +import java.util.List; + +@Service +public class SpringGameService { + + @Autowired + private GameDAO gameDAO; + + @Autowired + private RoomDAO roomDAO; + + public MoveResponseDTO initialize(int roomId) throws SQLException { + roomDAO.updateRoomColorById(roomId, Color.WHITE); + Pieces pieces = new Pieces(Pieces.initPieces()); + gameDAO.addAllPiecesById(roomId, pieces); + return new MoveResponseDTO(new PiecesResponseDTO(pieces).getPieces(), Color.WHITE, false); + } + + public MoveResponseDTO move(MoveRequestDTO requestDTO) throws SQLException { + Integer roomId = requestDTO.getRoomId(); + String sourcePosition = requestDTO.getSourcePosition(); + String targetPosition = requestDTO.getTargetPosition(); + + Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); + Color currentColor = roomDAO.findRoomColorById(roomId); + GameManager gameManager = new GameManager(pieces, currentColor); + gameManager.validateEndGame(); + gameManager.moveFromTo(Position.of(sourcePosition), Position.of(targetPosition)); + roomDAO.updateRoomColorById(roomId, gameManager.getCurrentColor()); + gameDAO.removeAllPiecesById(roomId); + gameDAO.addAllPiecesById(roomId, pieces); + return new MoveResponseDTO(new PiecesResponseDTO(pieces).getPieces(), roomDAO.findRoomColorById(roomId), + gameManager.isKingDead()); + } + + public double getScore(int roomId, Color color) throws SQLException { + Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); + GameManager gameManager = new GameManager(pieces, color); + + return PieceScore.calculateByColor(gameManager, color); + } + + public PiecesResponseDTO getPiecesResponseDTO(int roomId) throws SQLException { + Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); + return new PiecesResponseDTO(pieces); + } + + private boolean isKingDead(final int roomId) throws SQLException { + Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); + Color currentColor = roomDAO.findRoomColorById(roomId); + return pieces.isKingDead(currentColor); + } + + private Color getCurrentColor(final int roomId) throws SQLException { + return roomDAO.findRoomColorById(roomId); + } + + public List getMovablePositions(final int roomId, final String sourcePosition) throws SQLException { + Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); + GameManager gameManager = new GameManager(pieces, roomDAO.findRoomColorById(roomId)); + + return gameManager.getMovablePositions(Position.of(sourcePosition)); + } + + public MoveResponseDTO createMoveResponseDTO(final int roomId) throws SQLException { + return new MoveResponseDTO(getPiecesResponseDTO(roomId).getPieces(), + getCurrentColor(roomId), isKingDead(roomId)); + } +} diff --git a/src/main/java/wooteco/chess/service/RoomService.java b/src/main/java/wooteco/chess/service/SpringRoomService.java similarity index 76% rename from src/main/java/wooteco/chess/service/RoomService.java rename to src/main/java/wooteco/chess/service/SpringRoomService.java index 15a6780f4f..3cf2f4963d 100644 --- a/src/main/java/wooteco/chess/service/RoomService.java +++ b/src/main/java/wooteco/chess/service/SpringRoomService.java @@ -3,29 +3,26 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import wooteco.chess.dao.RoomDAO; +import wooteco.chess.domain.Color; import wooteco.chess.domain.room.Room; import java.sql.SQLException; import java.util.List; @Service -public class RoomService { +public class SpringRoomService { @Autowired private RoomDAO roomDAO; public void addRoom(String roomName) throws SQLException { - roomDAO.addRoom(roomName, "WHITE"); + roomDAO.addRoom(roomName, Color.WHITE.name()); } public void removeRoom(int roomId) throws SQLException { roomDAO.removeRoomById(roomId); } - public Room findRoom(int roomId) throws SQLException { - return roomDAO.findRoomById(roomId); - } - public List findAllRoom() throws SQLException { return roomDAO.findAllRoom(); } diff --git a/src/main/java/wooteco/chess/sparkcontroller/SparkGameController.java b/src/main/java/wooteco/chess/sparkcontroller/SparkGameController.java new file mode 100644 index 0000000000..87d98a5ef2 --- /dev/null +++ b/src/main/java/wooteco/chess/sparkcontroller/SparkGameController.java @@ -0,0 +1,97 @@ +package wooteco.chess.sparkcontroller; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import spark.Request; +import spark.Response; +import wooteco.chess.domain.Color; +import wooteco.chess.service.SparkGameService; + +import java.sql.SQLException; + +public class SparkGameController { + public static final String BASIC_URL = "/game"; + public static final String MOVE_URL = BASIC_URL + "/move"; + public static final String STATUS_URL = BASIC_URL + "/status"; + public static final String INIT_URL = BASIC_URL + "/init"; + public static final String LOAD_URL = BASIC_URL + "/load"; + public static final String GET_URL = BASIC_URL + "/get"; + + public static String initGame(Request request, Response response) throws SQLException { + SparkGameService gameService = SparkGameService.getInstance(); + int roomId = Integer.parseInt(request.queryParams("roomId")); + gameService.initialize(roomId); + + Gson gson = new Gson(); + JsonObject object = new JsonObject(); + String pieces = gson.toJson(gameService.getPiecesResponseDTO(roomId).getPieces()); + String currentColor = gameService.getCurrentColor(roomId); + + object.addProperty("pieces", pieces); + object.addProperty("currentColor", currentColor); + + return gson.toJson(object); + } + + public static String movePiece(Request request, Response response) throws SQLException { + SparkGameService gameService = SparkGameService.getInstance(); + + int roomId = Integer.parseInt(request.queryParams("roomId")); + String sourcePosition = request.queryParams("sourcePosition"); + String targetPosition = request.queryParams("targetPosition"); + gameService.movePiece(roomId, sourcePosition, targetPosition); + boolean kingDead = gameService.isKingDead(roomId); + String currentColor = gameService.getCurrentColor(roomId); + + Gson gson = new Gson(); + JsonObject object = new JsonObject(); + String pieces = gson.toJson(gameService.getPiecesResponseDTO(roomId).getPieces()); + + object.addProperty("pieces", pieces); + object.addProperty("kingDead", kingDead); + object.addProperty("currentColor", currentColor); + + return gson.toJson(object); + } + + public static String showStatus(Request request, Response response) throws SQLException { + SparkGameService gameService = SparkGameService.getInstance(); + int roomId = Integer.parseInt(request.queryParams("roomId")); + + double whiteScore = gameService.getScore(roomId, Color.WHITE); + double blackScore = gameService.getScore(roomId, Color.BLACK); + + Gson gson = new Gson(); + JsonObject object = new JsonObject(); + + object.addProperty("whiteScore", whiteScore); + object.addProperty("blackScore", blackScore); + + return gson.toJson(object); + } + + public static String loadGame(Request request, Response response) throws SQLException { + SparkGameService gameService = SparkGameService.getInstance(); + int roomId = Integer.parseInt(request.queryParams("roomId")); + + Gson gson = new Gson(); + JsonObject object = new JsonObject(); + String pieces = gson.toJson(gameService.getPiecesResponseDTO(roomId).getPieces()); + String currentColor = gameService.getCurrentColor(roomId); + + object.addProperty("pieces", pieces); + object.addProperty("currentColor", currentColor); + + return gson.toJson(object); + } + + public static String getMovablePositions(final Request request, final Response response) throws SQLException { + SparkGameService gameService = SparkGameService.getInstance(); + int roomId = Integer.parseInt(request.queryParams("roomId")); + String sourcePosition = request.queryParams("sourcePosition"); + + Gson gson = new Gson(); + + return gson.toJson(gameService.getMovablePositions(roomId, sourcePosition)); + } +} diff --git a/src/main/java/wooteco/chess/sparkcontroller/SparkRoomController.java b/src/main/java/wooteco/chess/sparkcontroller/SparkRoomController.java new file mode 100644 index 0000000000..cc21a2e285 --- /dev/null +++ b/src/main/java/wooteco/chess/sparkcontroller/SparkRoomController.java @@ -0,0 +1,55 @@ +package wooteco.chess.sparkcontroller; + +import spark.Route; +import wooteco.chess.domain.room.Room; +import wooteco.chess.service.SparkRoomService; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static wooteco.chess.util.HandlebarsUtil.render; + +public class SparkRoomController { + public static final String BASIC_URL = "/rooms"; + public static final String ENTER_ROOM_URL = BASIC_URL + "/enter"; + public static final String CREATE_ROOM_URL = BASIC_URL + "/create"; + public static final String REMOVE_ROOM_URL = BASIC_URL + "/remove"; + + public static Route getAllRoom = (request, response) -> { + Map model = new HashMap<>(); + + SparkRoomService roomService = SparkRoomService.getInstance(); + List rooms = roomService.findAllRoom(); + model.put("rooms", rooms); + + return render(model, "index.html"); + }; + + public static Route enterRoom = (request, response) -> { + Map model = new HashMap<>(); + model.put("roomId", request.queryParams("roomId")); + + return render(model, "game.html"); + }; + + public static Route createRoom = (request, response) -> { + SparkRoomService roomService = SparkRoomService.getInstance(); + String param = request.queryParams("roomName"); + roomService.addRoom(param); + + response.redirect("/rooms"); + return null; + }; + + public static Route removeRoom = (request, response) -> { + SparkRoomService roomService = SparkRoomService.getInstance(); + roomService.removeRoom(Integer.parseInt(request.queryParams("roomId"))); + + response.redirect("/rooms"); + return null; + }; + + private SparkRoomController() { + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 436effa585..701bfc4705 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,5 +1,4 @@ spring.h2.console.enabled=true - spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:13306/chess?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8 spring.datasource.username=root diff --git a/src/main/resources/banner.txt b/src/main/resources/banner.txt new file mode 100644 index 0000000000..b48a522e0d --- /dev/null +++ b/src/main/resources/banner.txt @@ -0,0 +1,9 @@ + ('-. .-. ('-. _ .-') _ _ .-') _ +( OO ) / _( OO) ( ( OO) )( ( OO) ) +,--. ,--.(,------.,--. ,--. .-'),-----. \ .'_ \ .'_ +| | | | | .---'| |.-') | |.-') ( OO' .-. ' .-') ,`'--..._),`'--..._) +| .| | | | | | OO ) | | OO )/ | | | | _( OO) | | \ '| | \ ' +| |(| '--. | |`-' | | |`-' |\_) | |\| | (,------. | | ' || | ' | +| .-. | | .--'(| '---.'(| '---.' \ | | | | '------' | | / :| | / : +| | | | | `---.| | | | `' '-' ' | '--' /| '--' / +`--' `--' `------'`------' `------' `-----' `-------' `-------' \ No newline at end of file diff --git a/src/main/resources/logback-access.xml b/src/main/resources/logback-access.xml index d6a1c32200..7be2110b11 100644 --- a/src/main/resources/logback-access.xml +++ b/src/main/resources/logback-access.xml @@ -5,5 +5,5 @@ - + \ No newline at end of file diff --git a/src/main/resources/static/css/index.css b/src/main/resources/static/css/index.css index 8aedba4110..34cc44f88f 100644 --- a/src/main/resources/static/css/index.css +++ b/src/main/resources/static/css/index.css @@ -13,10 +13,11 @@ background: #D4B66A; } -.title{ +.title { margin: 50px 0 50px 0; text-align: center; } + #overlay { position: fixed; display: none; diff --git a/src/main/resources/templates/game.hbs b/src/main/resources/templates/game.hbs index b26cb19c50..3383d6b83e 100644 --- a/src/main/resources/templates/game.hbs +++ b/src/main/resources/templates/game.hbs @@ -149,19 +149,23 @@ addBorder(movablePosition); }); } + function cancelMovablePosition(movablePositions) { movablePositions.forEach(function (movablePosition) { removeBorder(movablePosition); }); } + function addBorder(movablePosition) { let element = document.getElementById(movablePosition); addClass(element, "movable"); } + function removeBorder(movablePosition) { let element = document.getElementById(movablePosition); removeClass(element, "movable"); } + function getMovablePosition(sourcePosition) { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { @@ -174,33 +178,41 @@ xhr.open('GET', '/game/get?roomId={{roomId}}&sourcePosition=' + sourcePosition, true); xhr.send(); } + function applyPieces(pieces) { pieces.forEach(function (piece) { applyBackgroundImg(piece.position, piece.imgUrl); }); } + function applyBackgroundImg(piecePosition, pieceImgUrl) { let element = document.getElementById(piecePosition); element.style.backgroundImage = "url(/img/" + pieceImgUrl + ")"; element.style.backgroundSize = "cover"; } + function showStatus(whiteScore, blackScore) { alert("현재 White의 점수 : " + whiteScore + "\n" + "현재 Black의 점수 : " + blackScore); } + function addBlur() { let containerValue = document.getElementById("all"); addClass(containerValue, "blur"); } + function removeBlur() { let containerValue = document.getElementById("all"); removeClass(containerValue, "blur"); } + function addOverlay() { document.getElementById("overlay").style.display = "block"; } + function removeOverlay() { document.getElementById("overlay").style.display = "none"; } + // TODO : 임시방편 왕이 죽는 순간 Turn도 바뀌지 않고 끝나야 함. function applyWinnerColor(currentColor) { if (currentColor === "WHITE") { @@ -209,9 +221,11 @@ document.getElementById("winner").innerText = "WHITE"; } } + function showCurrentColor(currentColor) { document.getElementById("turn").innerText = currentColor; } + function isKingDead(currentColor, kingDead) { if (kingDead === true) { addOverlay(); @@ -219,6 +233,7 @@ applyWinnerColor(currentColor); } } + document.getElementById("initButton").addEventListener('click', function () { init(); }); @@ -233,7 +248,8 @@ xhr.open('GET', '/game/status?roomId={{roomId}}', true); xhr.send(); }); - function move(sourcePosition, targetPosition) { + + function move(source, target) { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { @@ -250,13 +266,16 @@ } } }; - xhr.open('POST', '/game/move?roomId={{roomId}}&sourcePosition=' - + sourcePosition - + '&targetPosition=' - + targetPosition, - true); - xhr.send(); + let data = { + roomId: {{roomId}}, + sourcePosition: source, + targetPosition: target, + }; + xhr.open('POST', '/game/move', true); + xhr.setRequestHeader('Content-Type', 'application/json'); + xhr.send(JSON.stringify(data)); } + for (let i = 0; i < allChessPosition.length; i++) { allChessPosition[i].addEventListener('click', function () { if (!isChooseSourcePosition) { @@ -279,22 +298,23 @@ removeBlur(); removeOverlay(); }); + function load() { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { let chessJson = JSON.parse(xhr.responseText); let pieces = chessJson.pieces; - if(pieces.length === 64) { + if (pieces.length === 64) { let isLoad = confirm("저장된 게임이 이미 있습니다! 불러올까요?"); - if(isLoad) { + if (isLoad) { applyPieces(pieces); showCurrentColor(chessJson.currentColor); alert("정상적으로 불러왔습니다!"); } else { init(); } - }else { + } else { init(); } } @@ -302,6 +322,7 @@ xhr.open('GET', '/game/load?roomId={{roomId}}', true); xhr.send(); } + function init() { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { @@ -315,6 +336,7 @@ xhr.open('GET', '/game/init?roomId={{roomId}}', true); xhr.send(); } + load(); } diff --git a/src/main/resources/templates/game.html b/src/main/resources/templates/game.html new file mode 100644 index 0000000000..554717d8e9 --- /dev/null +++ b/src/main/resources/templates/game.html @@ -0,0 +1,339 @@ + + + + + + + + + + + + +
+
+

가 이겼습니다!

+
+
+ +
+

이곳은 {{roomId}}번 방입니다!

+ +
현재 턴은 입니다.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
8
7
6
5
4
3
2
1
abcdefgh
+
+ + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/index.hbs b/src/main/resources/templates/index.hbs index 6984e62373..6e354dbb6d 100644 --- a/src/main/resources/templates/index.hbs +++ b/src/main/resources/templates/index.hbs @@ -57,7 +57,7 @@ {{#if errors}} -
방 제목은 한 글자 이상이어야 합니다.
+
방 제목은 한 글자 이상이어야 합니다.
{{/if}} @@ -84,13 +84,13 @@ console.log("deleteRoom : " + roomId); let currentPath = window.location.pathname; - location.href = currentPath + '/remove?roomId=' + roomId; + location.href = currentPath + '/remove?roomId=' + roomId; } function enterRoom(roomId) { console.log("enterRoom : " + roomId); let currentPath = window.location.pathname; - location.href = currentPath + '/enter?roomId=' + roomId; + location.href = currentPath + '/enter?roomId=' + roomId; } diff --git a/src/main/resources/templates/index.html b/src/main/resources/templates/index.html new file mode 100644 index 0000000000..fd2cbbbc91 --- /dev/null +++ b/src/main/resources/templates/index.html @@ -0,0 +1,84 @@ + + + + + + + + + + + + +
+

전체 방 목록

+ + {{#if rooms}} + + + + + + + + + + {{#each rooms}} + + + + + + {{/each}} + +
방 번호방 제목삭제(새로고침해야 적용됩니다...)
{{this.roomId}}{{this.roomName}} + +
+ {{else}} +

방이 하나도 개설되지 않았습니다!

+ {{/if}} + +
+
+ 방을 만드려면 방 제목을 입력해주세요. + +
+ +
+ +
+
+ 방에 입장하려면 방 번호를 입력해주세요. + +
+ +
+
+ + + + + \ No newline at end of file diff --git a/src/test/java/wooteco/chess/ChessApplicationTests.java b/src/test/java/wooteco/chess/ChessApplicationTests.java index 27559d30f6..4f8681d142 100644 --- a/src/test/java/wooteco/chess/ChessApplicationTests.java +++ b/src/test/java/wooteco/chess/ChessApplicationTests.java @@ -6,8 +6,8 @@ @SpringBootTest class ChessApplicationTests { - @Test - void contextLoads() { - } + @Test + void contextLoads() { + } } diff --git a/src/test/java/wooteco/chess/domain/ColorTest.java b/src/test/java/wooteco/chess/domain/ColorTest.java index dd9945109b..02602c965d 100644 --- a/src/test/java/wooteco/chess/domain/ColorTest.java +++ b/src/test/java/wooteco/chess/domain/ColorTest.java @@ -7,10 +7,10 @@ class ColorTest { - @DisplayName("반대의 컬러를 반환하는지 확인하는 테스트") - @Test - void reverseTest() { - assertThat(Color.WHITE.reverse()).isEqualTo(Color.BLACK); - assertThat(Color.BLACK.reverse()).isEqualTo(Color.WHITE); - } + @DisplayName("반대의 컬러를 반환하는지 확인하는 테스트") + @Test + void reverseTest() { + assertThat(Color.WHITE.reverse()).isEqualTo(Color.BLACK); + assertThat(Color.BLACK.reverse()).isEqualTo(Color.WHITE); + } } \ No newline at end of file diff --git a/src/test/java/wooteco/chess/domain/PieceScoreTest.java b/src/test/java/wooteco/chess/domain/PieceScoreTest.java index 02b23349a4..2640f85981 100644 --- a/src/test/java/wooteco/chess/domain/PieceScoreTest.java +++ b/src/test/java/wooteco/chess/domain/PieceScoreTest.java @@ -9,23 +9,23 @@ import static org.assertj.core.api.Assertions.assertThat; public class PieceScoreTest { - @DisplayName("최종적으로 각 팀의 점수를 계산해 제대로 나오는지 확인하는 테스트") - @Test - void calculateTeamTest() { - Pieces pieces = new Pieces(Pieces.initPieces()); + @DisplayName("최종적으로 각 팀의 점수를 계산해 제대로 나오는지 확인하는 테스트") + @Test + void calculateTeamTest() { + Pieces pieces = new Pieces(Pieces.initPieces()); - pieces.addPiece(Position.of("a3"), new Pawn(Color.WHITE, "p")); - pieces.addPiece(Position.of("a4"), new Pawn(Color.WHITE, "p")); - pieces.addPiece(Position.of("b6"), new Pawn(Color.BLACK, "P")); - pieces.addPiece(Position.of("f6"), new Pawn(Color.BLACK, "P")); - pieces.addPiece(Position.of("f5"), new Pawn(Color.BLACK, "P")); + pieces.addPiece(Position.of("a3"), new Pawn(Color.WHITE, "p")); + pieces.addPiece(Position.of("a4"), new Pawn(Color.WHITE, "p")); + pieces.addPiece(Position.of("b6"), new Pawn(Color.BLACK, "P")); + pieces.addPiece(Position.of("f6"), new Pawn(Color.BLACK, "P")); + pieces.addPiece(Position.of("f5"), new Pawn(Color.BLACK, "P")); - GameManager gameManager = new GameManager(pieces, Color.WHITE); + GameManager gameManager = new GameManager(pieces, Color.WHITE); - double whiteScore = PieceScore.calculateByColor(gameManager, Color.WHITE); - double blackScore = PieceScore.calculateByColor(gameManager, Color.BLACK); + double whiteScore = PieceScore.calculateByColor(gameManager, Color.WHITE); + double blackScore = PieceScore.calculateByColor(gameManager, Color.BLACK); - assertThat(whiteScore).isEqualTo(38.5); - assertThat(blackScore).isEqualTo(38.5); - } + assertThat(whiteScore).isEqualTo(38.5); + assertThat(blackScore).isEqualTo(38.5); + } } diff --git a/src/test/java/wooteco/chess/domain/board/GameManagerTest.java b/src/test/java/wooteco/chess/domain/board/GameManagerTest.java index 75cfe643eb..5cc046055d 100644 --- a/src/test/java/wooteco/chess/domain/board/GameManagerTest.java +++ b/src/test/java/wooteco/chess/domain/board/GameManagerTest.java @@ -14,105 +14,105 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; public class GameManagerTest { - private GameManager gameManager; - private Pieces pieces; - - @BeforeEach - void setUp() { - pieces = new Pieces(Pieces.initPieces()); - gameManager = new GameManager(pieces, Color.WHITE); - } - - @DisplayName("체스판을 생성하면 초기화 상태로 들어가있는지 테스트") - @Test - void initializeBoardTest() { - - assertThat(gameManager.getPiece("e1")).isInstanceOf(King.class); - assertThat(gameManager.getPiece("d1")).isInstanceOf(Queen.class); - assertThat(gameManager.getPiece("b1")).isInstanceOf(Knight.class); - assertThat(gameManager.getPiece("g1")).isInstanceOf(Knight.class); - assertThat(gameManager.getPiece("c1")).isInstanceOf(Bishop.class); - assertThat(gameManager.getPiece("f1")).isInstanceOf(Bishop.class); - assertThat(gameManager.getPiece("a1")).isInstanceOf(Rook.class); - assertThat(gameManager.getPiece("h1")).isInstanceOf(Rook.class); - - for (Column column : Column.values()) { - assertThat(gameManager.getPiece(column.getColumn() + "2")).isInstanceOf(Pawn.class); - } - - assertThat(gameManager.getPiece("e8")).isInstanceOf(King.class); - assertThat(gameManager.getPiece("d8")).isInstanceOf(Queen.class); - assertThat(gameManager.getPiece("b8")).isInstanceOf(Knight.class); - assertThat(gameManager.getPiece("g8")).isInstanceOf(Knight.class); - assertThat(gameManager.getPiece("c8")).isInstanceOf(Bishop.class); - assertThat(gameManager.getPiece("f8")).isInstanceOf(Bishop.class); - assertThat(gameManager.getPiece("a8")).isInstanceOf(Rook.class); - assertThat(gameManager.getPiece("h8")).isInstanceOf(Rook.class); - - for (Column column : Column.values()) { - assertThat(gameManager.getPiece(column.getColumn() + "7")).isInstanceOf(Pawn.class); - } - } - - @DisplayName("폰이 대각선으로 상대방 말이 있을 경우, 먹으면서 이동하는 경우 테스트") - @Test - void pawnCatchDiagonalTest() { - GameManager gameManager; - Map pieces = new HashMap<>(); - PiecesFactory.createBlankPieces(pieces); - Pieces board = new Pieces(pieces); - - Pawn whitePawn = new Pawn(Color.WHITE, "p"); - Pawn blackPawn = new Pawn(Color.BLACK, "P"); - - board.addPiece(Position.of("d4"), whitePawn); - board.addPiece(Position.of("e5"), blackPawn); - - gameManager = new GameManager(board, Color.WHITE); - - gameManager.moveFromTo(Position.of("d4"), Position.of("e5")); - assertThat(gameManager.getPiece("e5")).isEqualTo(whitePawn); - assertThat(gameManager.getPiece("d4").isBlank()).isTrue(); - } - - @DisplayName("해당 위치에 있는 piece가 원하는 target으로 갈 수 있는 List를 반환하는 것을 테스트") - @Test - void moveFromToTest() { - gameManager.moveFromTo(Position.of("b1"), Position.of("a3")); - assertThat(gameManager.getPiece("a3")).isInstanceOf(Knight.class); - assertThat(gameManager.getPiece("b1").isBlank()).isTrue(); - } - - @DisplayName("source position 을 상대방 말로 선택했을 경우") - @Test - void validateOtherPieceSourcePositionTest() { - assertThatThrownBy(() -> { - gameManager.moveFromTo(Position.of("b8"), Position.of("a4")); - }).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("상대방의 말을 선택하셨습니다"); - } - - @DisplayName("target position 을 자신의 말로 선택했을 경우") - @Test - void validateSameColorTargetPositionTest() { - assertThatThrownBy(() -> { - gameManager.moveFromTo(Position.of("b1"), Position.of("d2")); - }).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("target에 자신의 말이 있습니다"); - } - - @DisplayName("target position 을 해당 말로 갈 수 없는 곳으 선택했을 경우") - @Test - void validateNotMovablePositionTest() { - assertThatThrownBy(() -> { - gameManager.moveFromTo(Position.of("b1"), Position.of("a4")); - }).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("갈 수 없는 곳을 선택하셨습니다"); - } - - @DisplayName("초기화 상태일 때 King이 안 죽었는지 확인하는 테스트") - @Test - void isKingDeadTest() { - assertThat(gameManager.isKingDead()).isFalse(); - } + private GameManager gameManager; + private Pieces pieces; + + @BeforeEach + void setUp() { + pieces = new Pieces(Pieces.initPieces()); + gameManager = new GameManager(pieces, Color.WHITE); + } + + @DisplayName("체스판을 생성하면 초기화 상태로 들어가있는지 테스트") + @Test + void initializeBoardTest() { + + assertThat(gameManager.getPiece("e1")).isInstanceOf(King.class); + assertThat(gameManager.getPiece("d1")).isInstanceOf(Queen.class); + assertThat(gameManager.getPiece("b1")).isInstanceOf(Knight.class); + assertThat(gameManager.getPiece("g1")).isInstanceOf(Knight.class); + assertThat(gameManager.getPiece("c1")).isInstanceOf(Bishop.class); + assertThat(gameManager.getPiece("f1")).isInstanceOf(Bishop.class); + assertThat(gameManager.getPiece("a1")).isInstanceOf(Rook.class); + assertThat(gameManager.getPiece("h1")).isInstanceOf(Rook.class); + + for (Column column : Column.values()) { + assertThat(gameManager.getPiece(column.getColumn() + "2")).isInstanceOf(Pawn.class); + } + + assertThat(gameManager.getPiece("e8")).isInstanceOf(King.class); + assertThat(gameManager.getPiece("d8")).isInstanceOf(Queen.class); + assertThat(gameManager.getPiece("b8")).isInstanceOf(Knight.class); + assertThat(gameManager.getPiece("g8")).isInstanceOf(Knight.class); + assertThat(gameManager.getPiece("c8")).isInstanceOf(Bishop.class); + assertThat(gameManager.getPiece("f8")).isInstanceOf(Bishop.class); + assertThat(gameManager.getPiece("a8")).isInstanceOf(Rook.class); + assertThat(gameManager.getPiece("h8")).isInstanceOf(Rook.class); + + for (Column column : Column.values()) { + assertThat(gameManager.getPiece(column.getColumn() + "7")).isInstanceOf(Pawn.class); + } + } + + @DisplayName("폰이 대각선으로 상대방 말이 있을 경우, 먹으면서 이동하는 경우 테스트") + @Test + void pawnCatchDiagonalTest() { + GameManager gameManager; + Map pieces = new HashMap<>(); + PiecesFactory.createBlankPieces(pieces); + Pieces board = new Pieces(pieces); + + Pawn whitePawn = new Pawn(Color.WHITE, "p"); + Pawn blackPawn = new Pawn(Color.BLACK, "P"); + + board.addPiece(Position.of("d4"), whitePawn); + board.addPiece(Position.of("e5"), blackPawn); + + gameManager = new GameManager(board, Color.WHITE); + + gameManager.moveFromTo(Position.of("d4"), Position.of("e5")); + assertThat(gameManager.getPiece("e5")).isEqualTo(whitePawn); + assertThat(gameManager.getPiece("d4").isBlank()).isTrue(); + } + + @DisplayName("해당 위치에 있는 piece가 원하는 target으로 갈 수 있는 List를 반환하는 것을 테스트") + @Test + void moveFromToTest() { + gameManager.moveFromTo(Position.of("b1"), Position.of("a3")); + assertThat(gameManager.getPiece("a3")).isInstanceOf(Knight.class); + assertThat(gameManager.getPiece("b1").isBlank()).isTrue(); + } + + @DisplayName("source position 을 상대방 말로 선택했을 경우") + @Test + void validateOtherPieceSourcePositionTest() { + assertThatThrownBy(() -> { + gameManager.moveFromTo(Position.of("b8"), Position.of("a4")); + }).isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("상대방의 말을 선택하셨습니다"); + } + + @DisplayName("target position 을 자신의 말로 선택했을 경우") + @Test + void validateSameColorTargetPositionTest() { + assertThatThrownBy(() -> { + gameManager.moveFromTo(Position.of("b1"), Position.of("d2")); + }).isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("target에 자신의 말이 있습니다"); + } + + @DisplayName("target position 을 해당 말로 갈 수 없는 곳으 선택했을 경우") + @Test + void validateNotMovablePositionTest() { + assertThatThrownBy(() -> { + gameManager.moveFromTo(Position.of("b1"), Position.of("a4")); + }).isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("갈 수 없는 곳을 선택하셨습니다"); + } + + @DisplayName("초기화 상태일 때 King이 안 죽었는지 확인하는 테스트") + @Test + void isKingDeadTest() { + assertThat(gameManager.isKingDead()).isFalse(); + } } diff --git a/src/test/java/wooteco/chess/domain/board/PositionTest.java b/src/test/java/wooteco/chess/domain/board/PositionTest.java index da92f45486..6e5408a36a 100644 --- a/src/test/java/wooteco/chess/domain/board/PositionTest.java +++ b/src/test/java/wooteco/chess/domain/board/PositionTest.java @@ -8,25 +8,25 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; public class PositionTest { - @DisplayName("of 메서드에 대해서 File과 Rank가 같을 때 하나의 Position 인스턴스만 생성되는지 확인") - @Test - void ofTest() { - assertThat(Position.of("a1")).isEqualTo(Position.of("a1")); - assertThat(Position.of(Column.A, Row.ONE)).isEqualTo(Position.of("a1")); - assertThat(Position.of(8, 1)).isEqualTo(Position.of("a1")); - } + @DisplayName("of 메서드에 대해서 File과 Rank가 같을 때 하나의 Position 인스턴스만 생성되는지 확인") + @Test + void ofTest() { + assertThat(Position.of("a1")).isEqualTo(Position.of("a1")); + assertThat(Position.of(Column.A, Row.ONE)).isEqualTo(Position.of("a1")); + assertThat(Position.of(8, 1)).isEqualTo(Position.of("a1")); + } - @DisplayName("of 메서드에 대해서 체스판 범위 밖의 값을 입력했을 때 예외처리") - @Test - void ofExceptionTest() { - assertThatThrownBy(() -> { - Position.of("a9"); - }).isInstanceOf(IllegalArgumentException.class); - } + @DisplayName("of 메서드에 대해서 체스판 범위 밖의 값을 입력했을 때 예외처리") + @Test + void ofExceptionTest() { + assertThatThrownBy(() -> { + Position.of("a9"); + }).isInstanceOf(IllegalArgumentException.class); + } - @Test - void isInitialPawnPosition() { - assertThat(Position.of("a2").isInitialPawnPosition(Color.WHITE)).isTrue(); - assertThat(Position.of("b7").isInitialPawnPosition(Color.BLACK)).isTrue(); - } + @Test + void isInitialPawnPosition() { + assertThat(Position.of("a2").isInitialPawnPosition(Color.WHITE)).isTrue(); + assertThat(Position.of("b7").isInitialPawnPosition(Color.BLACK)).isTrue(); + } } diff --git a/src/test/java/wooteco/chess/domain/piece/BishopTest.java b/src/test/java/wooteco/chess/domain/piece/BishopTest.java index a564bdcdff..5bf8de8256 100644 --- a/src/test/java/wooteco/chess/domain/piece/BishopTest.java +++ b/src/test/java/wooteco/chess/domain/piece/BishopTest.java @@ -15,44 +15,44 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; class BishopTest { - Map originPiece; - Pieces pieces; - GameManager gameManager; - - @BeforeEach - void setUp() { - originPiece = new HashMap<>(); - PiecesFactory.createBlankPieces(originPiece); - pieces = new Pieces(originPiece); - gameManager = new GameManager(pieces, Color.WHITE); - } - - @DisplayName("Bishop 클래스가 PieceScore에 있는 Enum Bishop과 동일한지 테스트") - @Test - void isSameNameTest() { - Bishop bishop = new Bishop(Color.WHITE, "b"); - assertThat(bishop.isSameName(PieceScore.BISHOP)).isTrue(); - } - - @DisplayName("비숍이 대각선으로 가는지 테스트") - @Test - void goTest() { - Bishop bishop = new Bishop(Color.WHITE, "b"); - pieces.addPiece(Position.of("b2"), bishop); - - gameManager.moveFromTo(Position.of("b2"), Position.of("h8")); - - assertThat(pieces.getPieceByPosition(Position.of("h8"))).isEqualTo(bishop); - } - - @DisplayName("비숍이 못 가는 곳 테스트") - @Test - void goExceptionTest() { - Bishop bishop = new Bishop(Color.WHITE, "b"); - pieces.addPiece(Position.of("b2"), bishop); - - assertThatThrownBy(() -> { - gameManager.moveFromTo(Position.of("b2"), Position.of("h2")); - }).isInstanceOf(IllegalArgumentException.class); - } + Map originPiece; + Pieces pieces; + GameManager gameManager; + + @BeforeEach + void setUp() { + originPiece = new HashMap<>(); + PiecesFactory.createBlankPieces(originPiece); + pieces = new Pieces(originPiece); + gameManager = new GameManager(pieces, Color.WHITE); + } + + @DisplayName("Bishop 클래스가 PieceScore에 있는 Enum Bishop과 동일한지 테스트") + @Test + void isSameNameTest() { + Bishop bishop = new Bishop(Color.WHITE, "b"); + assertThat(bishop.isSameName(PieceScore.BISHOP)).isTrue(); + } + + @DisplayName("비숍이 대각선으로 가는지 테스트") + @Test + void goTest() { + Bishop bishop = new Bishop(Color.WHITE, "b"); + pieces.addPiece(Position.of("b2"), bishop); + + gameManager.moveFromTo(Position.of("b2"), Position.of("h8")); + + assertThat(pieces.getPieceByPosition(Position.of("h8"))).isEqualTo(bishop); + } + + @DisplayName("비숍이 못 가는 곳 테스트") + @Test + void goExceptionTest() { + Bishop bishop = new Bishop(Color.WHITE, "b"); + pieces.addPiece(Position.of("b2"), bishop); + + assertThatThrownBy(() -> { + gameManager.moveFromTo(Position.of("b2"), Position.of("h2")); + }).isInstanceOf(IllegalArgumentException.class); + } } \ No newline at end of file diff --git a/src/test/java/wooteco/chess/domain/piece/BlankTest.java b/src/test/java/wooteco/chess/domain/piece/BlankTest.java index 7993978eb0..df400cd934 100644 --- a/src/test/java/wooteco/chess/domain/piece/BlankTest.java +++ b/src/test/java/wooteco/chess/domain/piece/BlankTest.java @@ -7,19 +7,19 @@ import static org.assertj.core.api.Assertions.assertThat; class BlankTest { - @DisplayName("빈 값을 가져오는지 테스트") - @Test - void of() { - Piece blank = Blank.getInstance(); - assertThat(blank).isInstanceOf(Blank.class); - } + @DisplayName("빈 값을 가져오는지 테스트") + @Test + void of() { + Piece blank = Blank.getInstance(); + assertThat(blank).isInstanceOf(Blank.class); + } - @DisplayName("해당 Piece가 빈 값인지 아닌지 테스트") - @Test - void isBlankTest() { - Piece blank = Blank.getInstance(); - Piece pawn = new Pawn(Color.WHITE, "p"); - assertThat(blank.isBlank()).isTrue(); - assertThat(pawn.isBlank()).isFalse(); - } + @DisplayName("해당 Piece가 빈 값인지 아닌지 테스트") + @Test + void isBlankTest() { + Piece blank = Blank.getInstance(); + Piece pawn = new Pawn(Color.WHITE, "p"); + assertThat(blank.isBlank()).isTrue(); + assertThat(pawn.isBlank()).isFalse(); + } } \ No newline at end of file diff --git a/src/test/java/wooteco/chess/domain/piece/KingTest.java b/src/test/java/wooteco/chess/domain/piece/KingTest.java index 33bf766813..58f9c92c2b 100644 --- a/src/test/java/wooteco/chess/domain/piece/KingTest.java +++ b/src/test/java/wooteco/chess/domain/piece/KingTest.java @@ -15,44 +15,44 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; class KingTest { - Map originPiece; - Pieces pieces; - GameManager gameManager; - - @BeforeEach - void setUp() { - originPiece = new HashMap<>(); - PiecesFactory.createBlankPieces(originPiece); - pieces = new Pieces(originPiece); - gameManager = new GameManager(pieces, Color.WHITE); - } - - @DisplayName("King 클래스가 PieceScore에 있는 Enum King 동일한지 테스트") - @Test - void isSameNameTest() { - King king = new King(Color.WHITE, "k"); - assertThat(king.isSameName(PieceScore.KING)).isTrue(); - } - - @DisplayName("왕이 대각선으로 가는지 테스트") - @Test - void goBlockTest() { - King king = new King(Color.WHITE, "k"); - pieces.addPiece(Position.of("b2"), king); - - gameManager.moveFromTo(Position.of("b2"), Position.of("c3")); - - assertThat(pieces.getPieceByPosition(Position.of("c3"))).isEqualTo(king); - } - - @DisplayName("왕이 못 가는 곳 테스트") - @Test - void goExceptionTest() { - King king = new King(Color.WHITE, "k"); - pieces.addPiece(Position.of("b2"), king); - - assertThatThrownBy(() -> { - gameManager.moveFromTo(Position.of("b2"), Position.of("h2")); - }).isInstanceOf(IllegalArgumentException.class); - } + Map originPiece; + Pieces pieces; + GameManager gameManager; + + @BeforeEach + void setUp() { + originPiece = new HashMap<>(); + PiecesFactory.createBlankPieces(originPiece); + pieces = new Pieces(originPiece); + gameManager = new GameManager(pieces, Color.WHITE); + } + + @DisplayName("King 클래스가 PieceScore에 있는 Enum King 동일한지 테스트") + @Test + void isSameNameTest() { + King king = new King(Color.WHITE, "k"); + assertThat(king.isSameName(PieceScore.KING)).isTrue(); + } + + @DisplayName("왕이 대각선으로 가는지 테스트") + @Test + void goBlockTest() { + King king = new King(Color.WHITE, "k"); + pieces.addPiece(Position.of("b2"), king); + + gameManager.moveFromTo(Position.of("b2"), Position.of("c3")); + + assertThat(pieces.getPieceByPosition(Position.of("c3"))).isEqualTo(king); + } + + @DisplayName("왕이 못 가는 곳 테스트") + @Test + void goExceptionTest() { + King king = new King(Color.WHITE, "k"); + pieces.addPiece(Position.of("b2"), king); + + assertThatThrownBy(() -> { + gameManager.moveFromTo(Position.of("b2"), Position.of("h2")); + }).isInstanceOf(IllegalArgumentException.class); + } } \ No newline at end of file diff --git a/src/test/java/wooteco/chess/domain/piece/KnightTest.java b/src/test/java/wooteco/chess/domain/piece/KnightTest.java index 07d8128702..5a75058ba7 100644 --- a/src/test/java/wooteco/chess/domain/piece/KnightTest.java +++ b/src/test/java/wooteco/chess/domain/piece/KnightTest.java @@ -15,44 +15,44 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; class KnightTest { - Map originPiece; - Pieces pieces; - GameManager gameManager; - - @BeforeEach - void setUp() { - originPiece = new HashMap<>(); - PiecesFactory.createBlankPieces(originPiece); - pieces = new Pieces(originPiece); - gameManager = new GameManager(pieces, Color.WHITE); - } - - @DisplayName("Knight 클래스가 PieceScore에 있는 Enum Knight 동일한지 테스트") - @Test - void isSameNameTest() { - Knight knight = new Knight(Color.WHITE, "n"); - assertThat(knight.isSameName(PieceScore.KNIGHT)).isTrue(); - } - - @DisplayName("Knight이 대각선으로 가는지 테스트") - @Test - void goTest() { - Knight knight = new Knight(Color.WHITE, "n"); - pieces.addPiece(Position.of("b2"), knight); - - gameManager.moveFromTo(Position.of("b2"), Position.of("d3")); - - assertThat(pieces.getPieceByPosition(Position.of("d3"))).isEqualTo(knight); - } - - @DisplayName("Knight이 못 가는 곳 테스트") - @Test - void goExceptionTest() { - Knight knight = new Knight(Color.WHITE, "n"); - pieces.addPiece(Position.of("b2"), knight); - - assertThatThrownBy(() -> { - gameManager.moveFromTo(Position.of("b2"), Position.of("h2")); - }).isInstanceOf(IllegalArgumentException.class); - } + Map originPiece; + Pieces pieces; + GameManager gameManager; + + @BeforeEach + void setUp() { + originPiece = new HashMap<>(); + PiecesFactory.createBlankPieces(originPiece); + pieces = new Pieces(originPiece); + gameManager = new GameManager(pieces, Color.WHITE); + } + + @DisplayName("Knight 클래스가 PieceScore에 있는 Enum Knight 동일한지 테스트") + @Test + void isSameNameTest() { + Knight knight = new Knight(Color.WHITE, "n"); + assertThat(knight.isSameName(PieceScore.KNIGHT)).isTrue(); + } + + @DisplayName("Knight이 대각선으로 가는지 테스트") + @Test + void goTest() { + Knight knight = new Knight(Color.WHITE, "n"); + pieces.addPiece(Position.of("b2"), knight); + + gameManager.moveFromTo(Position.of("b2"), Position.of("d3")); + + assertThat(pieces.getPieceByPosition(Position.of("d3"))).isEqualTo(knight); + } + + @DisplayName("Knight이 못 가는 곳 테스트") + @Test + void goExceptionTest() { + Knight knight = new Knight(Color.WHITE, "n"); + pieces.addPiece(Position.of("b2"), knight); + + assertThatThrownBy(() -> { + gameManager.moveFromTo(Position.of("b2"), Position.of("h2")); + }).isInstanceOf(IllegalArgumentException.class); + } } \ No newline at end of file diff --git a/src/test/java/wooteco/chess/domain/piece/PawnTest.java b/src/test/java/wooteco/chess/domain/piece/PawnTest.java index 104df98620..ad1647c392 100644 --- a/src/test/java/wooteco/chess/domain/piece/PawnTest.java +++ b/src/test/java/wooteco/chess/domain/piece/PawnTest.java @@ -14,62 +14,62 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; class PawnTest { - Map originPiece; - Pieces pieces; - GameManager gameManager; - - @BeforeEach - void setUp() { - originPiece = new HashMap<>(); - PiecesFactory.createBlankPieces(originPiece); - pieces = new Pieces(originPiece); - gameManager = new GameManager(pieces, Color.WHITE); - } - - @DisplayName("폰이 처음으로 두 칸 갈 수 있는지 하는지 테스트") - @Test - void goTwoBlockTest() { - Pawn pawn = new Pawn(Color.WHITE, "p"); - pieces.addPiece(Position.of("b2"), pawn); - - gameManager.moveFromTo(Position.of("b2"), Position.of("b4")); - - assertThat(pieces.getPieceByPosition(Position.of("b4"))).isEqualTo(pawn); - } - - @DisplayName("폰이 한 칸을 갈 수 있는지 테스트") - @Test - void goOneBlockTest() { - Pawn pawn = new Pawn(Color.WHITE, "p"); - pieces.addPiece(Position.of("b2"), pawn); - - gameManager.moveFromTo(Position.of("b2"), Position.of("b3")); - - assertThat(pieces.getPieceByPosition(Position.of("b3"))).isEqualTo(pawn); - } - - @DisplayName("폰이 대각선으로 적군이 있을 때 먹을 수 있는지 테스트") - @Test - void eatOneBlockTest() { - Pawn whitePawn = new Pawn(Color.WHITE, "p"); - Pawn blackPawn = new Pawn(Color.BLACK, "p"); - - pieces.addPiece(Position.of("b2"), whitePawn); - pieces.addPiece(Position.of("c3"), blackPawn); - pieces.addPiece(Position.of("d2"), blackPawn); - - gameManager.moveFromTo(Position.of("b2"), Position.of("c3")); - assertThat(pieces.getPieceByPosition(Position.of("c3"))).isEqualTo(whitePawn); - } - - @DisplayName("이외 폰이 갈 수 없는 방향 테스트") - @Test - void goExceptionTest() { - Pawn pawn = new Pawn(Color.WHITE, "p"); - pieces.addPiece(Position.of("b2"), pawn); - - assertThatThrownBy(() -> { - gameManager.moveFromTo(Position.of("b2"), Position.of("b5")); - }).isInstanceOf(IllegalArgumentException.class); - } + Map originPiece; + Pieces pieces; + GameManager gameManager; + + @BeforeEach + void setUp() { + originPiece = new HashMap<>(); + PiecesFactory.createBlankPieces(originPiece); + pieces = new Pieces(originPiece); + gameManager = new GameManager(pieces, Color.WHITE); + } + + @DisplayName("폰이 처음으로 두 칸 갈 수 있는지 하는지 테스트") + @Test + void goTwoBlockTest() { + Pawn pawn = new Pawn(Color.WHITE, "p"); + pieces.addPiece(Position.of("b2"), pawn); + + gameManager.moveFromTo(Position.of("b2"), Position.of("b4")); + + assertThat(pieces.getPieceByPosition(Position.of("b4"))).isEqualTo(pawn); + } + + @DisplayName("폰이 한 칸을 갈 수 있는지 테스트") + @Test + void goOneBlockTest() { + Pawn pawn = new Pawn(Color.WHITE, "p"); + pieces.addPiece(Position.of("b2"), pawn); + + gameManager.moveFromTo(Position.of("b2"), Position.of("b3")); + + assertThat(pieces.getPieceByPosition(Position.of("b3"))).isEqualTo(pawn); + } + + @DisplayName("폰이 대각선으로 적군이 있을 때 먹을 수 있는지 테스트") + @Test + void eatOneBlockTest() { + Pawn whitePawn = new Pawn(Color.WHITE, "p"); + Pawn blackPawn = new Pawn(Color.BLACK, "p"); + + pieces.addPiece(Position.of("b2"), whitePawn); + pieces.addPiece(Position.of("c3"), blackPawn); + pieces.addPiece(Position.of("d2"), blackPawn); + + gameManager.moveFromTo(Position.of("b2"), Position.of("c3")); + assertThat(pieces.getPieceByPosition(Position.of("c3"))).isEqualTo(whitePawn); + } + + @DisplayName("이외 폰이 갈 수 없는 방향 테스트") + @Test + void goExceptionTest() { + Pawn pawn = new Pawn(Color.WHITE, "p"); + pieces.addPiece(Position.of("b2"), pawn); + + assertThatThrownBy(() -> { + gameManager.moveFromTo(Position.of("b2"), Position.of("b5")); + }).isInstanceOf(IllegalArgumentException.class); + } } \ No newline at end of file diff --git a/src/test/java/wooteco/chess/domain/piece/PieceTest.java b/src/test/java/wooteco/chess/domain/piece/PieceTest.java index 4afeb83c88..8859d6bb12 100644 --- a/src/test/java/wooteco/chess/domain/piece/PieceTest.java +++ b/src/test/java/wooteco/chess/domain/piece/PieceTest.java @@ -8,44 +8,43 @@ import static org.assertj.core.api.Assertions.assertThat; /** - * - * @author AnHyungJu, LeeHoBin + * @author AnHyungJu, LeeHoBin */ public class PieceTest { - @DisplayName("Piece의 색깔과 같은 색깔인지 확인하는 테스트") - @Test - void isSameColorTest() { - Piece piece = new King(Color.BLACK, "K"); - - assertThat(piece.isSameColor(Color.BLACK)).isTrue(); - assertThat(piece.isSameColor(Color.WHITE)).isFalse(); - } - - @DisplayName("Piece와 PieceScore에 있는 이름과 같은지 확인하는 테스트") - @Test - void isSameNameTest() { - Piece piece = new King(Color.BLACK, "K"); - - assertThat(piece.isSameName(PieceScore.KING)).isTrue(); - } - - @DisplayName("Piece가 Pawn인지 확인하는 테스트") - @Test - void isPawnTest() { - Piece pawn = new Pawn(Color.BLACK, "P"); - Piece king = new King(Color.BLACK, "K"); - - assertThat(pawn.isPawn()).isTrue(); - assertThat(king.isPawn()).isFalse(); - } - - @DisplayName("Piece가 King인지 확인하는 테스트") - @Test - void isKingTest() { - Piece pawn = new Pawn(Color.BLACK, "P"); - Piece king = new King(Color.BLACK, "K"); - - assertThat(pawn.isKing()).isFalse(); - assertThat(king.isKing()).isTrue(); - } + @DisplayName("Piece의 색깔과 같은 색깔인지 확인하는 테스트") + @Test + void isSameColorTest() { + Piece piece = new King(Color.BLACK, "K"); + + assertThat(piece.isSameColor(Color.BLACK)).isTrue(); + assertThat(piece.isSameColor(Color.WHITE)).isFalse(); + } + + @DisplayName("Piece와 PieceScore에 있는 이름과 같은지 확인하는 테스트") + @Test + void isSameNameTest() { + Piece piece = new King(Color.BLACK, "K"); + + assertThat(piece.isSameName(PieceScore.KING)).isTrue(); + } + + @DisplayName("Piece가 Pawn인지 확인하는 테스트") + @Test + void isPawnTest() { + Piece pawn = new Pawn(Color.BLACK, "P"); + Piece king = new King(Color.BLACK, "K"); + + assertThat(pawn.isPawn()).isTrue(); + assertThat(king.isPawn()).isFalse(); + } + + @DisplayName("Piece가 King인지 확인하는 테스트") + @Test + void isKingTest() { + Piece pawn = new Pawn(Color.BLACK, "P"); + Piece king = new King(Color.BLACK, "K"); + + assertThat(pawn.isKing()).isFalse(); + assertThat(king.isKing()).isTrue(); + } } diff --git a/src/test/java/wooteco/chess/domain/piece/QueenTest.java b/src/test/java/wooteco/chess/domain/piece/QueenTest.java index 8d4bf757d0..dda18df7ad 100644 --- a/src/test/java/wooteco/chess/domain/piece/QueenTest.java +++ b/src/test/java/wooteco/chess/domain/piece/QueenTest.java @@ -15,55 +15,55 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; class QueenTest { - Map originPiece; - Pieces pieces; - GameManager gameManager; + Map originPiece; + Pieces pieces; + GameManager gameManager; - @BeforeEach - void setUp() { - originPiece = new HashMap<>(); - PiecesFactory.createBlankPieces(originPiece); - pieces = new Pieces(originPiece); - gameManager = new GameManager(pieces, Color.WHITE); - } + @BeforeEach + void setUp() { + originPiece = new HashMap<>(); + PiecesFactory.createBlankPieces(originPiece); + pieces = new Pieces(originPiece); + gameManager = new GameManager(pieces, Color.WHITE); + } - @DisplayName("Queen 클래스가 PieceScore에 있는 Enum Queen 동일한지 테스트") - @Test - void isSameNameTest() { - Queen queen = new Queen(Color.WHITE, "q"); - assertThat(queen.isSameName(PieceScore.QUEEN)).isTrue(); - } + @DisplayName("Queen 클래스가 PieceScore에 있는 Enum Queen 동일한지 테스트") + @Test + void isSameNameTest() { + Queen queen = new Queen(Color.WHITE, "q"); + assertThat(queen.isSameName(PieceScore.QUEEN)).isTrue(); + } - @DisplayName("Queen이 대각선으로 가는지 테스트") - @Test - void goDiagonalTest() { - Queen queen = new Queen(Color.WHITE, "q"); - pieces.addPiece(Position.of("b2"), queen); + @DisplayName("Queen이 대각선으로 가는지 테스트") + @Test + void goDiagonalTest() { + Queen queen = new Queen(Color.WHITE, "q"); + pieces.addPiece(Position.of("b2"), queen); - gameManager.moveFromTo(Position.of("b2"), Position.of("h8")); + gameManager.moveFromTo(Position.of("b2"), Position.of("h8")); - assertThat(pieces.getPieceByPosition(Position.of("h8"))).isEqualTo(queen); - } + assertThat(pieces.getPieceByPosition(Position.of("h8"))).isEqualTo(queen); + } - @DisplayName("Queen이 선으로 가는지 테스트") - @Test - void goDirectTest() { - Queen queen = new Queen(Color.WHITE, "q"); - pieces.addPiece(Position.of("b2"), queen); + @DisplayName("Queen이 선으로 가는지 테스트") + @Test + void goDirectTest() { + Queen queen = new Queen(Color.WHITE, "q"); + pieces.addPiece(Position.of("b2"), queen); - gameManager.moveFromTo(Position.of("b2"), Position.of("h2")); + gameManager.moveFromTo(Position.of("b2"), Position.of("h2")); - assertThat(pieces.getPieceByPosition(Position.of("h2"))).isEqualTo(queen); - } + assertThat(pieces.getPieceByPosition(Position.of("h2"))).isEqualTo(queen); + } - @DisplayName("Queen이 못 가는 곳 테스트") - @Test - void goExceptionTest() { - Queen queen = new Queen(Color.WHITE, "q"); - pieces.addPiece(Position.of("b2"), queen); + @DisplayName("Queen이 못 가는 곳 테스트") + @Test + void goExceptionTest() { + Queen queen = new Queen(Color.WHITE, "q"); + pieces.addPiece(Position.of("b2"), queen); - assertThatThrownBy(() -> { - gameManager.moveFromTo(Position.of("b2"), Position.of("d3")); - }).isInstanceOf(IllegalArgumentException.class); - } + assertThatThrownBy(() -> { + gameManager.moveFromTo(Position.of("b2"), Position.of("d3")); + }).isInstanceOf(IllegalArgumentException.class); + } } \ No newline at end of file diff --git a/src/test/java/wooteco/chess/domain/piece/RookTest.java b/src/test/java/wooteco/chess/domain/piece/RookTest.java index 0be10b12c5..b73f83962f 100644 --- a/src/test/java/wooteco/chess/domain/piece/RookTest.java +++ b/src/test/java/wooteco/chess/domain/piece/RookTest.java @@ -15,44 +15,44 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; class RookTest { - Map originPiece; - Pieces pieces; - GameManager gameManager; - - @BeforeEach - void setUp() { - originPiece = new HashMap<>(); - PiecesFactory.createBlankPieces(originPiece); - pieces = new Pieces(originPiece); - gameManager = new GameManager(pieces, Color.WHITE); - } - - @DisplayName("Rook 클래스가 PieceScore에 있는 Enum Rook 동일한지 테스트") - @Test - void isSameNameTest() { - Rook rook = new Rook(Color.WHITE, "n"); - assertThat(rook.isSameName(PieceScore.ROOK)).isTrue(); - } - - @DisplayName("Rook이 대각선으로 가는지 테스트") - @Test - void goTest() { - Rook rook = new Rook(Color.WHITE, "n"); - pieces.addPiece(Position.of("b2"), rook); - - gameManager.moveFromTo(Position.of("b2"), Position.of("h2")); - - assertThat(pieces.getPieceByPosition(Position.of("h2"))).isEqualTo(rook); - } - - @DisplayName("Rook이 못 가는 곳 테스트") - @Test - void goExceptionTest() { - Rook rook = new Rook(Color.WHITE, "n"); - pieces.addPiece(Position.of("b2"), rook); - - assertThatThrownBy(() -> { - gameManager.moveFromTo(Position.of("b2"), Position.of("h3")); - }).isInstanceOf(IllegalArgumentException.class); - } + Map originPiece; + Pieces pieces; + GameManager gameManager; + + @BeforeEach + void setUp() { + originPiece = new HashMap<>(); + PiecesFactory.createBlankPieces(originPiece); + pieces = new Pieces(originPiece); + gameManager = new GameManager(pieces, Color.WHITE); + } + + @DisplayName("Rook 클래스가 PieceScore에 있는 Enum Rook 동일한지 테스트") + @Test + void isSameNameTest() { + Rook rook = new Rook(Color.WHITE, "n"); + assertThat(rook.isSameName(PieceScore.ROOK)).isTrue(); + } + + @DisplayName("Rook이 대각선으로 가는지 테스트") + @Test + void goTest() { + Rook rook = new Rook(Color.WHITE, "n"); + pieces.addPiece(Position.of("b2"), rook); + + gameManager.moveFromTo(Position.of("b2"), Position.of("h2")); + + assertThat(pieces.getPieceByPosition(Position.of("h2"))).isEqualTo(rook); + } + + @DisplayName("Rook이 못 가는 곳 테스트") + @Test + void goExceptionTest() { + Rook rook = new Rook(Color.WHITE, "n"); + pieces.addPiece(Position.of("b2"), rook); + + assertThatThrownBy(() -> { + gameManager.moveFromTo(Position.of("b2"), Position.of("h3")); + }).isInstanceOf(IllegalArgumentException.class); + } } \ No newline at end of file diff --git a/src/test/java/wooteco/chess/util/JDBCConnectorTest.java b/src/test/java/wooteco/chess/util/JDBCConnectorTest.java index 6c90eab636..da536aba6d 100644 --- a/src/test/java/wooteco/chess/util/JDBCConnectorTest.java +++ b/src/test/java/wooteco/chess/util/JDBCConnectorTest.java @@ -8,10 +8,10 @@ import static org.assertj.core.api.Assertions.assertThat; public class JDBCConnectorTest { - @DisplayName("JDBC Connection 테스트") - @Test - public void connection() { - Connection con = JDBCConnector.getConnection(); - assertThat(con).isNotNull(); - } + @DisplayName("JDBC Connection 테스트") + @Test + public void connection() { + Connection con = JDBCConnector.getConnection(); + assertThat(con).isNotNull(); + } }