From b087bd555ecf902fdd24031c1cd7f2bb7e3c8c87 Mon Sep 17 00:00:00 2001 From: DD <48818566+fucct@users.noreply.github.com> Date: Thu, 23 Apr 2020 17:08:28 +0900 Subject: [PATCH 01/10] =?UTF-8?q?[=EB=94=94=EB=94=94]=20=EC=B2=B4=EC=8A=A4?= =?UTF-8?q?=20=EC=8A=A4=ED=94=84=EB=A7=81=20=EC=8B=A4=EC=8A=B5=201?= =?UTF-8?q?=EB=8B=A8=EA=B3=84=20=EC=A0=9C=EC=B6=9C=ED=95=A9=EB=8B=88?= =?UTF-8?q?=EB=8B=A4.=20(#12)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 --- .../wooteco/chess/SparkChessApplication.java | 36 ++-- .../chess/controller/SparkGameController.java | 168 +++++++++--------- .../chess/controller/SparkRoomController.java | 71 ++++---- .../controller/SpringGameController.java | 92 ++++++---- src/main/java/wooteco/chess/dao/GameDAO.java | 8 +- .../java/wooteco/chess/dao/JdbcTemplate.java | 2 +- src/main/java/wooteco/chess/dao/RoomDAO.java | 8 +- .../java/wooteco/chess/dao/RowMapper.java | 4 +- .../wooteco/chess/domain/command/Command.java | 76 ++++++++ .../chess/domain/command/CommandType.java | 20 +++ .../chess/domain/command/FirstCommand.java | 49 +++++ .../wooteco/chess/domain/piece/Piece.java | 4 +- .../wooteco/chess/domain/piece/Pieces.java | 4 + .../piece/strategy/BasicOneMoveStrategy.java | 3 +- .../wooteco/chess/service/GameManagerDTO.java | 31 ++++ .../wooteco/chess/service/GameService.java | 33 ++-- .../wooteco/chess/service/RoomService.java | 11 +- .../wooteco/chess/util/JDBCConnector.java | 10 ++ .../java/wooteco/chess/view/InputView.java | 25 +++ .../java/wooteco/chess/view/OutputView.java | 52 ++++++ src/main/resources/templates/game.hbs | 44 ++++- 21 files changed, 543 insertions(+), 208 deletions(-) create mode 100644 src/main/java/wooteco/chess/domain/command/Command.java create mode 100644 src/main/java/wooteco/chess/domain/command/CommandType.java create mode 100644 src/main/java/wooteco/chess/domain/command/FirstCommand.java create mode 100644 src/main/java/wooteco/chess/service/GameManagerDTO.java create mode 100644 src/main/java/wooteco/chess/view/InputView.java create mode 100644 src/main/java/wooteco/chess/view/OutputView.java diff --git a/src/main/java/wooteco/chess/SparkChessApplication.java b/src/main/java/wooteco/chess/SparkChessApplication.java index feccbcf069..619a0f33e3 100644 --- a/src/main/java/wooteco/chess/SparkChessApplication.java +++ b/src/main/java/wooteco/chess/SparkChessApplication.java @@ -14,23 +14,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/controller/SparkGameController.java b/src/main/java/wooteco/chess/controller/SparkGameController.java index 479e42a625..eeb3794d29 100644 --- a/src/main/java/wooteco/chess/controller/SparkGameController.java +++ b/src/main/java/wooteco/chess/controller/SparkGameController.java @@ -10,88 +10,88 @@ 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)); -// } + 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 index f07b77f56b..ff0f1ebca9 100644 --- a/src/main/java/wooteco/chess/controller/SparkRoomController.java +++ b/src/main/java/wooteco/chess/controller/SparkRoomController.java @@ -16,40 +16,39 @@ public class SparkRoomController { 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() { -// } + 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..be689220bf 100644 --- a/src/main/java/wooteco/chess/controller/SpringGameController.java +++ b/src/main/java/wooteco/chess/controller/SpringGameController.java @@ -4,73 +4,91 @@ import com.google.gson.JsonObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; 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.GameManagerDTO; import wooteco.chess.service.GameService; -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 { +// public static final String MOVE_URL = BASIC_URL + "/move"; +// public static final String STATUS_URL = BASIC_URL + "/status"; +// public static final String GET_URL = BASIC_URL + "/get"; @Autowired private GameService gameService; @GetMapping("/init") - public GameManagerDTO init(@RequestParam(value = "roomId") Integer roomId) throws SQLException { + public GameManagerDTO init(@RequestParam(value = "roomId") Integer roomId, Model model) 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); - try { - gameService.movePiece(roomId, sourcePosition, targetPosition); - return gameService.createDTO(roomId); - } catch (IllegalArgumentException e) { - gameManagerDTO.setErrorMessage(e.getMessage()); - return gameManagerDTO; - } + 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); } - @GetMapping("/status") - public Model showStatus(@RequestParam Integer roomId, Model model) throws SQLException { + 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); - model.addAttribute("whiteScore", whiteScore); - model.addAttribute("blackScore", blackScore); + Gson gson = new Gson(); + JsonObject object = new JsonObject(); - return model; + object.addProperty("whiteScore", whiteScore); + object.addProperty("blackScore", blackScore); + + return gson.toJson(object); } @GetMapping("/load") - public GameManagerDTO load(@RequestParam Integer roomId) throws SQLException { - return gameService.createDTO(roomId); + public String load(@RequestParam Integer roomId) throws SQLException { + 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); } - @GetMapping("/get") - public List getMovablePositions(final HttpServletRequest request) throws SQLException { - int roomId = Integer.parseInt(request.getParameter("roomId")); - String sourcePosition = request.getParameter("sourcePosition"); + 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 gameService.getMovablePositions(roomId, sourcePosition); + return gson.toJson(gameService.getMovablePositions(roomId, sourcePosition)); } } diff --git a/src/main/java/wooteco/chess/dao/GameDAO.java b/src/main/java/wooteco/chess/dao/GameDAO.java index 39e0d69d2a..1c4d18fe8c 100644 --- a/src/main/java/wooteco/chess/dao/GameDAO.java +++ b/src/main/java/wooteco/chess/dao/GameDAO.java @@ -1,6 +1,5 @@ package wooteco.chess.dao; -import org.springframework.stereotype.Repository; import wooteco.chess.domain.board.Position; import wooteco.chess.domain.piece.Blank; import wooteco.chess.domain.piece.Piece; @@ -13,8 +12,13 @@ import java.util.HashMap; import java.util.Map; -@Repository public class GameDAO { + private static final GameDAO GAME_DAO = new GameDAO(); + + public static GameDAO getInstance() { + return GAME_DAO; + } + public void removeAllPiecesById(int roomId) throws SQLException { String query = "DELETE FROM board WHERE room_id = ?"; diff --git a/src/main/java/wooteco/chess/dao/JdbcTemplate.java b/src/main/java/wooteco/chess/dao/JdbcTemplate.java index 470e55b6ed..b65528135b 100644 --- a/src/main/java/wooteco/chess/dao/JdbcTemplate.java +++ b/src/main/java/wooteco/chess/dao/JdbcTemplate.java @@ -27,7 +27,7 @@ public void executeBatch(String query, PreparedStatementSetter pss) throws SQLEx } } - public T executeQuery(String query, PreparedStatementSetter pss, RowMapper rm) throws SQLException { + public Object executeQuery(String query, PreparedStatementSetter pss, RowMapper rm) throws SQLException { try (Connection con = JDBCConnector.getConnection(); PreparedStatement pstmt = con.prepareStatement(query) ) { diff --git a/src/main/java/wooteco/chess/dao/RoomDAO.java b/src/main/java/wooteco/chess/dao/RoomDAO.java index ccba67c364..cf40fc173b 100644 --- a/src/main/java/wooteco/chess/dao/RoomDAO.java +++ b/src/main/java/wooteco/chess/dao/RoomDAO.java @@ -1,6 +1,5 @@ package wooteco.chess.dao; -import org.springframework.stereotype.Repository; import wooteco.chess.domain.Color; import wooteco.chess.domain.room.Room; @@ -10,8 +9,13 @@ import java.util.ArrayList; import java.util.List; -@Repository public class RoomDAO { + private static final RoomDAO ROOM_DAO = new RoomDAO(); + + public static RoomDAO getInstance() { + return ROOM_DAO; + } + public void addRoom(String roomName, String roomColor) throws SQLException { String query = "INSERT INTO room(room_name, room_color) VALUES (?, ?)"; diff --git a/src/main/java/wooteco/chess/dao/RowMapper.java b/src/main/java/wooteco/chess/dao/RowMapper.java index e55741c2cb..2facca4b6d 100644 --- a/src/main/java/wooteco/chess/dao/RowMapper.java +++ b/src/main/java/wooteco/chess/dao/RowMapper.java @@ -3,6 +3,6 @@ import java.sql.ResultSet; import java.sql.SQLException; -public interface RowMapper { - T mapRow(final ResultSet rs) throws SQLException; +public interface RowMapper { + Object mapRow(final ResultSet rs) throws SQLException; } diff --git a/src/main/java/wooteco/chess/domain/command/Command.java b/src/main/java/wooteco/chess/domain/command/Command.java new file mode 100644 index 0000000000..ea97e58e87 --- /dev/null +++ b/src/main/java/wooteco/chess/domain/command/Command.java @@ -0,0 +1,76 @@ +package wooteco.chess.domain.command; + +import wooteco.chess.domain.board.Position; + +import java.util.Objects; + +/** + * class description + * + * @author AnHyungJu, LeeHoBin + */ +public class Command { + public static final int COMMAND_INDEX = 0; + public static final int BASIC_COMMAND_SIZE = 1; + public static final String DELIMITER = " "; + public static final int LIMIT = -1; + private static final int SOURCE_POSITION_INDEX = 1; + private static final int TARGET_POSITION_INDEX = 2; + private static final int MOVE_COMMAND_SIZE = 3; + private final String[] command; + + public Command(String input) { + String[] tempCommand = splitCommand(input); + validate(tempCommand); + command = tempCommand; + } + + private static void validateLength(String[] input) { + if (input.length != BASIC_COMMAND_SIZE && input.length != MOVE_COMMAND_SIZE) { + throw new IllegalArgumentException("명령문의 길이가 1 또는 3이어야합니다."); + } + } + + private String[] splitCommand(String input) { + return input.split(DELIMITER, LIMIT); + } + + private void validate(String[] input) { + validateLength(input); + validateNullAndEmpty(input[COMMAND_INDEX]); + validateStartOrEndOrMove(input[COMMAND_INDEX]); + } + + private void validateNullAndEmpty(String command) { + if (Objects.isNull(command) || command.isEmpty()) { + throw new IllegalArgumentException("null이나 빈 값은 들어올 수 없습니다."); + } + } + + private void validateStartOrEndOrMove(String input) { + if (!CommandType.MOVE.isSame(input) && !CommandType.END.isSame(input) && !CommandType.STATUS.isSame(input)) { + throw new IllegalArgumentException("명령은 move, status, end만 들어올 수 있습니다."); + } + } + + public Position getSourceCommand() { + return Position.of(command[SOURCE_POSITION_INDEX]); + } + + public Position getTargetCommand() { + return Position.of(command[TARGET_POSITION_INDEX]); + } + + public boolean isEnd() { + return CommandType.END.isSame(command[COMMAND_INDEX]); + } + + public boolean isStatus() { + return CommandType.STATUS.isSame(command[COMMAND_INDEX]); + } + + public boolean isMove() { + return CommandType.MOVE.isSame(command[COMMAND_INDEX]); + } + +} diff --git a/src/main/java/wooteco/chess/domain/command/CommandType.java b/src/main/java/wooteco/chess/domain/command/CommandType.java new file mode 100644 index 0000000000..d1d27b32d0 --- /dev/null +++ b/src/main/java/wooteco/chess/domain/command/CommandType.java @@ -0,0 +1,20 @@ +package wooteco.chess.domain.command; + +public enum CommandType { + START("start"), + STATUS("status"), + MOVE("move"), + END("end"); + + private final String command; + + CommandType(String command) { + this.command = command; + } + + public boolean isSame(String input) { + return this.command.equalsIgnoreCase(input); + } + + +} diff --git a/src/main/java/wooteco/chess/domain/command/FirstCommand.java b/src/main/java/wooteco/chess/domain/command/FirstCommand.java new file mode 100644 index 0000000000..a903bdfd25 --- /dev/null +++ b/src/main/java/wooteco/chess/domain/command/FirstCommand.java @@ -0,0 +1,49 @@ +package wooteco.chess.domain.command; + +import java.util.Objects; + +import static wooteco.chess.domain.command.Command.*; + +public class FirstCommand { + private final String command; + + public FirstCommand(String input) { + String[] tempCommand = splitCommand(input); + validate(tempCommand); + this.command = tempCommand[COMMAND_INDEX]; + } + + private String[] splitCommand(String input) { + validateNullAndEmpty(input); + return input.split(DELIMITER, LIMIT); + } + + private void validate(String[] input) { + validateLength(input); + String command = input[COMMAND_INDEX]; + validateNullAndEmpty(command); + validateStartOrEnd(command); + } + + private void validateNullAndEmpty(String command) { + if (Objects.isNull(command) || command.isEmpty()) { + throw new IllegalArgumentException("null이나 빈 값은 들어올 수 없습니다."); + } + } + + private void validateLength(String[] command) { + if (command.length != BASIC_COMMAND_SIZE) { + throw new IllegalArgumentException("처음 입력값은 Command 길이가 1이어야 합니다."); + } + } + + private void validateStartOrEnd(String input) { + if (!CommandType.START.isSame(input) && !CommandType.END.isSame(input)) { + throw new IllegalArgumentException("첫 명령은 start, end만 들어올 수 있습니다."); + } + } + + public boolean isEnd() { + return CommandType.END.isSame(command); + } +} diff --git a/src/main/java/wooteco/chess/domain/piece/Piece.java b/src/main/java/wooteco/chess/domain/piece/Piece.java index 21f6dedae1..c7a4ece178 100644 --- a/src/main/java/wooteco/chess/domain/piece/Piece.java +++ b/src/main/java/wooteco/chess/domain/piece/Piece.java @@ -13,8 +13,8 @@ * @author AnHyungJu, LeeHoBin */ public abstract class Piece { - protected final Color color; - protected final MoveStrategy moveStrategy; + protected Color color; + protected MoveStrategy moveStrategy; private final String symbol; public Piece(Color color, String symbol, MoveStrategy moveStrategy) { diff --git a/src/main/java/wooteco/chess/domain/piece/Pieces.java b/src/main/java/wooteco/chess/domain/piece/Pieces.java index b1653175e3..168e794ad8 100644 --- a/src/main/java/wooteco/chess/domain/piece/Pieces.java +++ b/src/main/java/wooteco/chess/domain/piece/Pieces.java @@ -37,6 +37,10 @@ public boolean isSameColor(Position position, Color currentColor) { return pieces.get(position).isSameColor(currentColor); } + public boolean isBlank(Position position) { + return pieces.get(position).isBlank(); + } + public Path movablePositions(Position sourcePosition) { Piece piece = pieces.get(sourcePosition); Path path = new Path(new ArrayList<>(), sourcePosition); diff --git a/src/main/java/wooteco/chess/domain/piece/strategy/BasicOneMoveStrategy.java b/src/main/java/wooteco/chess/domain/piece/strategy/BasicOneMoveStrategy.java index 2d72c1dfb5..f624fb690f 100644 --- a/src/main/java/wooteco/chess/domain/piece/strategy/BasicOneMoveStrategy.java +++ b/src/main/java/wooteco/chess/domain/piece/strategy/BasicOneMoveStrategy.java @@ -8,7 +8,8 @@ import java.util.List; import java.util.Map; -public class BasicOneMoveStrategy implements MoveStrategy { +public class +BasicOneMoveStrategy implements MoveStrategy { List directions; public BasicOneMoveStrategy(List directions) { diff --git a/src/main/java/wooteco/chess/service/GameManagerDTO.java b/src/main/java/wooteco/chess/service/GameManagerDTO.java new file mode 100644 index 0000000000..905e93e018 --- /dev/null +++ b/src/main/java/wooteco/chess/service/GameManagerDTO.java @@ -0,0 +1,31 @@ +package wooteco.chess.service; + +import wooteco.chess.domain.Color; +import wooteco.chess.dto.PieceResponseDTO; + +import java.util.List; +import java.util.Map; + +public class GameManagerDTO { + private final List pieces; + private final Color currentColor; + private final boolean kingDead; + + public GameManagerDTO(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; + } +} diff --git a/src/main/java/wooteco/chess/service/GameService.java b/src/main/java/wooteco/chess/service/GameService.java index 862de2aecd..e9b10b9fa2 100644 --- a/src/main/java/wooteco/chess/service/GameService.java +++ b/src/main/java/wooteco/chess/service/GameService.java @@ -1,6 +1,5 @@ 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; @@ -9,22 +8,27 @@ 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.Collection; import java.util.List; @Service public class GameService { + private static final GameService GAME_SERVICE = new GameService(); - @Autowired - private GameDAO gameDAO; + private GameService() { + } - @Autowired - private RoomDAO roomDAO; + public static GameService getInstance() { + return GAME_SERVICE; + } public GameManagerDTO initialize(int roomId) throws SQLException { + GameDAO gameDAO = GameDAO.getInstance(); + RoomDAO roomDAO = RoomDAO.getInstance(); + roomDAO.updateRoomColorById(roomId, Color.WHITE); Pieces pieces = new Pieces(Pieces.initPieces()); gameDAO.addAllPiecesById(roomId, pieces); @@ -32,6 +36,9 @@ public GameManagerDTO initialize(int roomId) throws SQLException { } public void movePiece(int roomId, String sourcePosition, String targetPosition) throws SQLException { + GameDAO gameDAO = GameDAO.getInstance(); + RoomDAO roomDAO = RoomDAO.getInstance(); + Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); GameManager gameManager = new GameManager(pieces, roomDAO.findRoomColorById(roomId)); gameManager.validateEndGame(); @@ -43,6 +50,7 @@ public void movePiece(int roomId, String sourcePosition, String targetPosition) } public double getScore(int roomId, Color color) throws SQLException { + GameDAO gameDAO = GameDAO.getInstance(); Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); GameManager gameManager = new GameManager(pieces, color); @@ -50,29 +58,32 @@ public double getScore(int roomId, Color color) throws SQLException { } public PiecesResponseDTO getPiecesResponseDTO(int roomId) throws SQLException { + GameDAO gameDAO = GameDAO.getInstance(); Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); return new PiecesResponseDTO(pieces); } public boolean isKingDead(final int roomId) throws SQLException { + GameDAO gameDAO = GameDAO.getInstance(); + RoomDAO roomDAO = RoomDAO.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 { + RoomDAO roomDAO = RoomDAO.getInstance(); return roomDAO.findRoomColorById(roomId).name(); } public List getMovablePositions(final int roomId, final String sourcePosition) throws SQLException { + GameDAO gameDAO = GameDAO.getInstance(); + RoomDAO roomDAO = RoomDAO.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/RoomService.java b/src/main/java/wooteco/chess/service/RoomService.java index 15a6780f4f..fff98bb20d 100644 --- a/src/main/java/wooteco/chess/service/RoomService.java +++ b/src/main/java/wooteco/chess/service/RoomService.java @@ -1,6 +1,5 @@ package wooteco.chess.service; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import wooteco.chess.dao.RoomDAO; import wooteco.chess.domain.room.Room; @@ -10,23 +9,29 @@ @Service public class RoomService { + private static final RoomService ROOM_SERVICE = new RoomService(); - @Autowired - private RoomDAO roomDAO; + public static RoomService getInstance() { + return ROOM_SERVICE; + } public void addRoom(String roomName) throws SQLException { + RoomDAO roomDAO = RoomDAO.getInstance(); roomDAO.addRoom(roomName, "WHITE"); } public void removeRoom(int roomId) throws SQLException { + RoomDAO roomDAO = RoomDAO.getInstance(); roomDAO.removeRoomById(roomId); } public Room findRoom(int roomId) throws SQLException { + RoomDAO roomDAO = RoomDAO.getInstance(); return roomDAO.findRoomById(roomId); } public List findAllRoom() throws SQLException { + RoomDAO roomDAO = RoomDAO.getInstance(); return roomDAO.findAllRoom(); } } diff --git a/src/main/java/wooteco/chess/util/JDBCConnector.java b/src/main/java/wooteco/chess/util/JDBCConnector.java index 9933909e27..ceda8892eb 100644 --- a/src/main/java/wooteco/chess/util/JDBCConnector.java +++ b/src/main/java/wooteco/chess/util/JDBCConnector.java @@ -30,4 +30,14 @@ public static Connection getConnection() { } return con; } + + public static void closeConnection(Connection con) { + try { + if (con != null) { + con.close(); + } + } catch (SQLException e) { + System.err.println("con 오류 : " + e.getMessage()); + } + } } diff --git a/src/main/java/wooteco/chess/view/InputView.java b/src/main/java/wooteco/chess/view/InputView.java new file mode 100644 index 0000000000..72f82461ad --- /dev/null +++ b/src/main/java/wooteco/chess/view/InputView.java @@ -0,0 +1,25 @@ +package wooteco.chess.view; + +import java.util.Scanner; + +/** + * @author AnHyungJu, LeeHoBin + */ +public class InputView { + private static final Scanner scanner = new Scanner(System.in); + + private InputView() { + } + + public static String inputCommand() { + try { + System.out.println("명령을 입력해주세요."); + return scanner.nextLine(); + } catch (IllegalArgumentException e) { + OutputView.printException(e); + return inputCommand(); + } + } + + +} diff --git a/src/main/java/wooteco/chess/view/OutputView.java b/src/main/java/wooteco/chess/view/OutputView.java new file mode 100644 index 0000000000..2d5ca46bc6 --- /dev/null +++ b/src/main/java/wooteco/chess/view/OutputView.java @@ -0,0 +1,52 @@ +package wooteco.chess.view; + +import wooteco.chess.domain.Color; +import wooteco.chess.domain.GameManager; +import wooteco.chess.domain.PieceScore; +import wooteco.chess.domain.board.Column; +import wooteco.chess.domain.board.Position; +import wooteco.chess.domain.board.Row; + +/** + * @author AnHyungJu, LeeHoBin + */ +public class OutputView { + public static final String BLANK_POSITION = "."; + + private OutputView() { + } + + public static void printGameInstruction() { + System.out.println("체스 게임을 시작합니다."); + System.out.println("게임 시작: start"); + System.out.println("게임 종료: end"); + System.out.println("게임 이동: move source위치 target위치 - 예. move b2 b3"); + } + + public static void printException(Exception e) { + System.out.println(e.getMessage()); + } + + public static void printGameEnd() { + System.out.println("게임을 종료합니다."); + } + + public static void printChessBoard(GameManager gameManager) { + for (Row row : Row.values()) { + for (Column column : Column.values()) { + Position position = Position.of(column, row); + if (gameManager.getPiece(column.getColumn() + row.getRow()).isBlank()) { + System.out.print(BLANK_POSITION); + continue; + } + System.out.print(gameManager.getPiece(column.getColumn() + row.getRow()).getSymbol()); + } + System.out.println(); + } + } + + public static void printStatus(GameManager gameManager) { + System.out.println("하얀색 진영의 점수 : " + PieceScore.calculateByColor(gameManager, Color.WHITE)); + System.out.println("검정색 진영의 점수 : " + PieceScore.calculateByColor(gameManager, Color.BLACK)); + } +} diff --git a/src/main/resources/templates/game.hbs b/src/main/resources/templates/game.hbs index b26cb19c50..c53646851b 100644 --- a/src/main/resources/templates/game.hbs +++ b/src/main/resources/templates/game.hbs @@ -141,27 +141,35 @@ let allChessPosition = document.querySelectorAll(".chessPosition"); let isChooseSourcePosition = false; let loadable = false; + let helloworld; + let sourcePosition; let movablePositions; + window.onload = function () { + function applyMovablePosition(movablePositions) { movablePositions.forEach(function (movablePosition) { 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 +182,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 +225,11 @@ document.getElementById("winner").innerText = "WHITE"; } } + function showCurrentColor(currentColor) { document.getElementById("turn").innerText = currentColor; } + function isKingDead(currentColor, kingDead) { if (kingDead === true) { addOverlay(); @@ -219,9 +237,11 @@ applyWinnerColor(currentColor); } } + document.getElementById("initButton").addEventListener('click', function () { init(); }); + document.getElementById("statusButton").addEventListener('click', function () { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { @@ -233,14 +253,13 @@ xhr.open('GET', '/game/status?roomId={{roomId}}', true); xhr.send(); }); + function move(sourcePosition, targetPosition) { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { let chessJson = JSON.parse(xhr.responseText); - console.log(chessJson); - console.log(chessJson.pieces); - if (chessJson.errorMessage == null) { + if (typeof chessJson.errorMessage == "undefined") { applyPieces(chessJson.pieces); let currentColor = chessJson.currentColor; isKingDead(currentColor, chessJson.kingDead); @@ -251,20 +270,23 @@ } }; xhr.open('POST', '/game/move?roomId={{roomId}}&sourcePosition=' - + sourcePosition - + '&targetPosition=' - + targetPosition, - true); + + sourcePosition + + '&targetPosition=' + + targetPosition, + true); xhr.send(); } + for (let i = 0; i < allChessPosition.length; i++) { allChessPosition[i].addEventListener('click', function () { if (!isChooseSourcePosition) { sourcePosition = allChessPosition[i].id; getMovablePosition(sourcePosition); } + }); } + for (let i = 0; i < allChessPosition.length; i++) { allChessPosition[i].addEventListener('click', function () { if (isChooseSourcePosition) { @@ -275,16 +297,18 @@ } }); } + document.getElementById("overlay").addEventListener('click', function () { 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; + let pieces = JSON.parse(chessJson.pieces); if(pieces.length === 64) { let isLoad = confirm("저장된 게임이 이미 있습니다! 불러올까요?"); if(isLoad) { @@ -302,6 +326,7 @@ xhr.open('GET', '/game/load?roomId={{roomId}}', true); xhr.send(); } + function init() { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { @@ -318,5 +343,6 @@ load(); } + - + \ No newline at end of file From fe807b4265e893af9be998bd84681970867b7426 Mon Sep 17 00:00:00 2001 From: DD <48818566+fucct@users.noreply.github.com> Date: Sun, 26 Apr 2020 13:09:46 +0900 Subject: [PATCH 02/10] =?UTF-8?q?[=EB=94=94=EB=94=94]=20=EC=B2=B4=EC=8A=A4?= =?UTF-8?q?=20-=20=EC=8A=A4=ED=94=84=EB=A7=81=20=EC=8B=A4=EC=8A=B5=202?= =?UTF-8?q?=EB=8B=A8=EA=B3=84=20=EC=A0=9C=EC=B6=9C=ED=95=A9=EB=8B=88?= =?UTF-8?q?=EB=8B=A4.=20(#73)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 --- .../wooteco/chess/SparkChessApplication.java | 5 +- .../wooteco/chess/SpringChessApplication.java | 7 +- .../controller/SpringGameController.java | 102 ++---- .../controller/SpringRoomController.java | 8 +- src/main/java/wooteco/chess/dao/GameDAO.java | 10 +- .../java/wooteco/chess/dao/JdbcTemplate.java | 2 +- src/main/java/wooteco/chess/dao/RoomDAO.java | 10 +- .../java/wooteco/chess/dao/RowMapper.java | 4 +- .../java/wooteco/chess/dao/SparkGameDAO.java | 157 ++++++++ .../java/wooteco/chess/dao/SparkRoomDAO.java | 166 +++++++++ .../wooteco/chess/domain/GameManager.java | 2 - .../wooteco/chess/domain/command/Command.java | 76 ---- .../chess/domain/command/CommandType.java | 20 -- .../chess/domain/command/FirstCommand.java | 49 --- .../wooteco/chess/domain/piece/Piece.java | 4 +- .../wooteco/chess/domain/piece/Pieces.java | 4 - .../piece/strategy/BasicOneMoveStrategy.java | 3 +- .../java/wooteco/chess/dto/GameStatusDTO.java | 19 + .../wooteco/chess/dto/MoveRequestDTO.java | 26 ++ .../MoveResponseDTO.java} | 17 +- .../chess/{controller => dto}/RoomName.java | 2 +- .../wooteco/chess/service/RoomService.java | 37 -- ...GameService.java => SparkGameService.java} | 41 +-- .../chess/service/SparkRoomService.java | 31 ++ .../chess/service/SpringGameService.java | 85 +++++ .../chess/service/SpringRoomService.java | 29 ++ .../SparkGameController.java | 16 +- .../SparkRoomController.java | 17 +- .../wooteco/chess/util/JDBCConnector.java | 10 - .../java/wooteco/chess/view/InputView.java | 25 -- .../java/wooteco/chess/view/OutputView.java | 52 --- 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 | 40 +-- 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 +- 53 files changed, 1530 insertions(+), 911 deletions(-) create mode 100644 src/main/java/wooteco/chess/dao/SparkGameDAO.java create mode 100644 src/main/java/wooteco/chess/dao/SparkRoomDAO.java delete mode 100644 src/main/java/wooteco/chess/domain/command/Command.java delete mode 100644 src/main/java/wooteco/chess/domain/command/CommandType.java delete mode 100644 src/main/java/wooteco/chess/domain/command/FirstCommand.java create mode 100644 src/main/java/wooteco/chess/dto/GameStatusDTO.java create mode 100644 src/main/java/wooteco/chess/dto/MoveRequestDTO.java rename src/main/java/wooteco/chess/{service/GameManagerDTO.java => dto/MoveResponseDTO.java} (56%) rename src/main/java/wooteco/chess/{controller => dto}/RoomName.java (91%) delete mode 100644 src/main/java/wooteco/chess/service/RoomService.java rename src/main/java/wooteco/chess/service/{GameService.java => SparkGameService.java} (68%) create mode 100644 src/main/java/wooteco/chess/service/SparkRoomService.java create mode 100644 src/main/java/wooteco/chess/service/SpringGameService.java create mode 100644 src/main/java/wooteco/chess/service/SpringRoomService.java rename src/main/java/wooteco/chess/{controller => sparkcontroller}/SparkGameController.java (85%) rename src/main/java/wooteco/chess/{controller => sparkcontroller}/SparkRoomController.java (77%) delete mode 100644 src/main/java/wooteco/chess/view/InputView.java delete mode 100644 src/main/java/wooteco/chess/view/OutputView.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 619a0f33e3..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) { 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/SpringGameController.java b/src/main/java/wooteco/chess/controller/SpringGameController.java index be689220bf..ececae641c 100644 --- a/src/main/java/wooteco/chess/controller/SpringGameController.java +++ b/src/main/java/wooteco/chess/controller/SpringGameController.java @@ -1,94 +1,60 @@ 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.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import spark.Request; -import spark.Response; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; import wooteco.chess.domain.Color; -import wooteco.chess.domain.GameManager; -import wooteco.chess.service.GameManagerDTO; -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 java.sql.SQLException; +import java.util.List; @RestController @RequestMapping("/game") public class SpringGameController { -// public static final String MOVE_URL = BASIC_URL + "/move"; -// public static final String STATUS_URL = BASIC_URL + "/status"; -// public static final String GET_URL = BASIC_URL + "/get"; - @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, Model model) throws SQLException { + public MoveResponseDTO init(@RequestParam Integer roomId) throws SQLException { return gameService.initialize(roomId); } - 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); + @PostMapping("/move") + public ResponseEntity move(@RequestBody MoveRequestDTO requestDTO) throws SQLException { + try { + return ResponseEntity.status(HttpStatus.OK).body(gameService.move(requestDTO)); + } catch (IllegalArgumentException e) { + MoveResponseDTO moveResponseDTO = gameService.createMoveResponseDTO(requestDTO.getRoomId()); + moveResponseDTO.setErrorMessage(e.getMessage()); + return ResponseEntity.status(HttpStatus.OK).body(moveResponseDTO); + } } - 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); + @GetMapping("/status") + public GameStatusDTO showStatus(@RequestParam Integer roomId) throws SQLException { + return new GameStatusDTO(gameService.getScore(roomId, Color.WHITE), gameService.getScore(roomId, Color.BLACK)); } @GetMapping("/load") - public String load(@RequestParam Integer roomId) throws SQLException { - 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 MoveResponseDTO load(@RequestParam Integer roomId) throws SQLException { + return gameService.createMoveResponseDTO(roomId); } - 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(); + @GetMapping("/get") + public List getMovablePositions(final HttpServletRequest request) throws SQLException { + int roomId = Integer.parseInt(request.getParameter("roomId")); + String sourcePosition = request.getParameter("sourcePosition"); - return gson.toJson(gameService.getMovablePositions(roomId, sourcePosition)); + return gameService.getMovablePositions(roomId, sourcePosition); } } 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 1c4d18fe8c..7b6dcd250b 100644 --- a/src/main/java/wooteco/chess/dao/GameDAO.java +++ b/src/main/java/wooteco/chess/dao/GameDAO.java @@ -1,24 +1,18 @@ package wooteco.chess.dao; +import org.springframework.stereotype.Repository; 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; +@Repository public class GameDAO { - private static final GameDAO GAME_DAO = new GameDAO(); - - public static GameDAO getInstance() { - return GAME_DAO; - } - public void removeAllPiecesById(int roomId) throws SQLException { String query = "DELETE FROM board WHERE room_id = ?"; diff --git a/src/main/java/wooteco/chess/dao/JdbcTemplate.java b/src/main/java/wooteco/chess/dao/JdbcTemplate.java index b65528135b..470e55b6ed 100644 --- a/src/main/java/wooteco/chess/dao/JdbcTemplate.java +++ b/src/main/java/wooteco/chess/dao/JdbcTemplate.java @@ -27,7 +27,7 @@ public void executeBatch(String query, PreparedStatementSetter pss) throws SQLEx } } - public Object executeQuery(String query, PreparedStatementSetter pss, RowMapper rm) throws SQLException { + public T executeQuery(String query, PreparedStatementSetter pss, RowMapper rm) throws SQLException { try (Connection con = JDBCConnector.getConnection(); PreparedStatement pstmt = con.prepareStatement(query) ) { diff --git a/src/main/java/wooteco/chess/dao/RoomDAO.java b/src/main/java/wooteco/chess/dao/RoomDAO.java index cf40fc173b..4377c14b7c 100644 --- a/src/main/java/wooteco/chess/dao/RoomDAO.java +++ b/src/main/java/wooteco/chess/dao/RoomDAO.java @@ -1,21 +1,15 @@ package wooteco.chess.dao; +import org.springframework.stereotype.Repository; 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; +@Repository public class RoomDAO { - private static final RoomDAO ROOM_DAO = new RoomDAO(); - - public static RoomDAO getInstance() { - return ROOM_DAO; - } - public void addRoom(String roomName, String roomColor) throws SQLException { String query = "INSERT INTO room(room_name, room_color) VALUES (?, ?)"; diff --git a/src/main/java/wooteco/chess/dao/RowMapper.java b/src/main/java/wooteco/chess/dao/RowMapper.java index 2facca4b6d..e55741c2cb 100644 --- a/src/main/java/wooteco/chess/dao/RowMapper.java +++ b/src/main/java/wooteco/chess/dao/RowMapper.java @@ -3,6 +3,6 @@ import java.sql.ResultSet; import java.sql.SQLException; -public interface RowMapper { - Object mapRow(final ResultSet rs) throws SQLException; +public interface RowMapper { + T mapRow(final ResultSet rs) throws SQLException; } 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/domain/command/Command.java b/src/main/java/wooteco/chess/domain/command/Command.java deleted file mode 100644 index ea97e58e87..0000000000 --- a/src/main/java/wooteco/chess/domain/command/Command.java +++ /dev/null @@ -1,76 +0,0 @@ -package wooteco.chess.domain.command; - -import wooteco.chess.domain.board.Position; - -import java.util.Objects; - -/** - * class description - * - * @author AnHyungJu, LeeHoBin - */ -public class Command { - public static final int COMMAND_INDEX = 0; - public static final int BASIC_COMMAND_SIZE = 1; - public static final String DELIMITER = " "; - public static final int LIMIT = -1; - private static final int SOURCE_POSITION_INDEX = 1; - private static final int TARGET_POSITION_INDEX = 2; - private static final int MOVE_COMMAND_SIZE = 3; - private final String[] command; - - public Command(String input) { - String[] tempCommand = splitCommand(input); - validate(tempCommand); - command = tempCommand; - } - - private static void validateLength(String[] input) { - if (input.length != BASIC_COMMAND_SIZE && input.length != MOVE_COMMAND_SIZE) { - throw new IllegalArgumentException("명령문의 길이가 1 또는 3이어야합니다."); - } - } - - private String[] splitCommand(String input) { - return input.split(DELIMITER, LIMIT); - } - - private void validate(String[] input) { - validateLength(input); - validateNullAndEmpty(input[COMMAND_INDEX]); - validateStartOrEndOrMove(input[COMMAND_INDEX]); - } - - private void validateNullAndEmpty(String command) { - if (Objects.isNull(command) || command.isEmpty()) { - throw new IllegalArgumentException("null이나 빈 값은 들어올 수 없습니다."); - } - } - - private void validateStartOrEndOrMove(String input) { - if (!CommandType.MOVE.isSame(input) && !CommandType.END.isSame(input) && !CommandType.STATUS.isSame(input)) { - throw new IllegalArgumentException("명령은 move, status, end만 들어올 수 있습니다."); - } - } - - public Position getSourceCommand() { - return Position.of(command[SOURCE_POSITION_INDEX]); - } - - public Position getTargetCommand() { - return Position.of(command[TARGET_POSITION_INDEX]); - } - - public boolean isEnd() { - return CommandType.END.isSame(command[COMMAND_INDEX]); - } - - public boolean isStatus() { - return CommandType.STATUS.isSame(command[COMMAND_INDEX]); - } - - public boolean isMove() { - return CommandType.MOVE.isSame(command[COMMAND_INDEX]); - } - -} diff --git a/src/main/java/wooteco/chess/domain/command/CommandType.java b/src/main/java/wooteco/chess/domain/command/CommandType.java deleted file mode 100644 index d1d27b32d0..0000000000 --- a/src/main/java/wooteco/chess/domain/command/CommandType.java +++ /dev/null @@ -1,20 +0,0 @@ -package wooteco.chess.domain.command; - -public enum CommandType { - START("start"), - STATUS("status"), - MOVE("move"), - END("end"); - - private final String command; - - CommandType(String command) { - this.command = command; - } - - public boolean isSame(String input) { - return this.command.equalsIgnoreCase(input); - } - - -} diff --git a/src/main/java/wooteco/chess/domain/command/FirstCommand.java b/src/main/java/wooteco/chess/domain/command/FirstCommand.java deleted file mode 100644 index a903bdfd25..0000000000 --- a/src/main/java/wooteco/chess/domain/command/FirstCommand.java +++ /dev/null @@ -1,49 +0,0 @@ -package wooteco.chess.domain.command; - -import java.util.Objects; - -import static wooteco.chess.domain.command.Command.*; - -public class FirstCommand { - private final String command; - - public FirstCommand(String input) { - String[] tempCommand = splitCommand(input); - validate(tempCommand); - this.command = tempCommand[COMMAND_INDEX]; - } - - private String[] splitCommand(String input) { - validateNullAndEmpty(input); - return input.split(DELIMITER, LIMIT); - } - - private void validate(String[] input) { - validateLength(input); - String command = input[COMMAND_INDEX]; - validateNullAndEmpty(command); - validateStartOrEnd(command); - } - - private void validateNullAndEmpty(String command) { - if (Objects.isNull(command) || command.isEmpty()) { - throw new IllegalArgumentException("null이나 빈 값은 들어올 수 없습니다."); - } - } - - private void validateLength(String[] command) { - if (command.length != BASIC_COMMAND_SIZE) { - throw new IllegalArgumentException("처음 입력값은 Command 길이가 1이어야 합니다."); - } - } - - private void validateStartOrEnd(String input) { - if (!CommandType.START.isSame(input) && !CommandType.END.isSame(input)) { - throw new IllegalArgumentException("첫 명령은 start, end만 들어올 수 있습니다."); - } - } - - public boolean isEnd() { - return CommandType.END.isSame(command); - } -} diff --git a/src/main/java/wooteco/chess/domain/piece/Piece.java b/src/main/java/wooteco/chess/domain/piece/Piece.java index c7a4ece178..21f6dedae1 100644 --- a/src/main/java/wooteco/chess/domain/piece/Piece.java +++ b/src/main/java/wooteco/chess/domain/piece/Piece.java @@ -13,8 +13,8 @@ * @author AnHyungJu, LeeHoBin */ public abstract class Piece { - protected Color color; - protected MoveStrategy moveStrategy; + protected final Color color; + protected final MoveStrategy moveStrategy; private final String symbol; public Piece(Color color, String symbol, MoveStrategy moveStrategy) { diff --git a/src/main/java/wooteco/chess/domain/piece/Pieces.java b/src/main/java/wooteco/chess/domain/piece/Pieces.java index 168e794ad8..b1653175e3 100644 --- a/src/main/java/wooteco/chess/domain/piece/Pieces.java +++ b/src/main/java/wooteco/chess/domain/piece/Pieces.java @@ -37,10 +37,6 @@ public boolean isSameColor(Position position, Color currentColor) { return pieces.get(position).isSameColor(currentColor); } - public boolean isBlank(Position position) { - return pieces.get(position).isBlank(); - } - public Path movablePositions(Position sourcePosition) { Piece piece = pieces.get(sourcePosition); Path path = new Path(new ArrayList<>(), sourcePosition); diff --git a/src/main/java/wooteco/chess/domain/piece/strategy/BasicOneMoveStrategy.java b/src/main/java/wooteco/chess/domain/piece/strategy/BasicOneMoveStrategy.java index f624fb690f..2d72c1dfb5 100644 --- a/src/main/java/wooteco/chess/domain/piece/strategy/BasicOneMoveStrategy.java +++ b/src/main/java/wooteco/chess/domain/piece/strategy/BasicOneMoveStrategy.java @@ -8,8 +8,7 @@ import java.util.List; import java.util.Map; -public class -BasicOneMoveStrategy implements MoveStrategy { +public class BasicOneMoveStrategy implements MoveStrategy { List directions; public BasicOneMoveStrategy(List directions) { 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/service/GameManagerDTO.java b/src/main/java/wooteco/chess/dto/MoveResponseDTO.java similarity index 56% rename from src/main/java/wooteco/chess/service/GameManagerDTO.java rename to src/main/java/wooteco/chess/dto/MoveResponseDTO.java index 905e93e018..bca29fa903 100644 --- a/src/main/java/wooteco/chess/service/GameManagerDTO.java +++ b/src/main/java/wooteco/chess/dto/MoveResponseDTO.java @@ -1,17 +1,16 @@ -package wooteco.chess.service; +package wooteco.chess.dto; import wooteco.chess.domain.Color; -import wooteco.chess.dto.PieceResponseDTO; import java.util.List; -import java.util.Map; -public class GameManagerDTO { +public class MoveResponseDTO { private final List pieces; private final Color currentColor; private final boolean kingDead; + private String errorMessage; - public GameManagerDTO(final List pieces, final Color currentColor, final boolean kingDead) { + public MoveResponseDTO(final List pieces, final Color currentColor, final boolean kingDead) { this.pieces = pieces; this.currentColor = currentColor; this.kingDead = kingDead; @@ -28,4 +27,12 @@ public Color getCurrentColor() { 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/RoomService.java b/src/main/java/wooteco/chess/service/RoomService.java deleted file mode 100644 index fff98bb20d..0000000000 --- a/src/main/java/wooteco/chess/service/RoomService.java +++ /dev/null @@ -1,37 +0,0 @@ -package wooteco.chess.service; - -import org.springframework.stereotype.Service; -import wooteco.chess.dao.RoomDAO; -import wooteco.chess.domain.room.Room; - -import java.sql.SQLException; -import java.util.List; - -@Service -public class RoomService { - private static final RoomService ROOM_SERVICE = new RoomService(); - - public static RoomService getInstance() { - return ROOM_SERVICE; - } - - public void addRoom(String roomName) throws SQLException { - RoomDAO roomDAO = RoomDAO.getInstance(); - roomDAO.addRoom(roomName, "WHITE"); - } - - public void removeRoom(int roomId) throws SQLException { - RoomDAO roomDAO = RoomDAO.getInstance(); - roomDAO.removeRoomById(roomId); - } - - public Room findRoom(int roomId) throws SQLException { - RoomDAO roomDAO = RoomDAO.getInstance(); - return roomDAO.findRoomById(roomId); - } - - public List findAllRoom() throws SQLException { - RoomDAO roomDAO = RoomDAO.getInstance(); - return roomDAO.findAllRoom(); - } -} diff --git a/src/main/java/wooteco/chess/service/GameService.java b/src/main/java/wooteco/chess/service/SparkGameService.java similarity index 68% rename from src/main/java/wooteco/chess/service/GameService.java rename to src/main/java/wooteco/chess/service/SparkGameService.java index e9b10b9fa2..d3a5907c52 100644 --- a/src/main/java/wooteco/chess/service/GameService.java +++ b/src/main/java/wooteco/chess/service/SparkGameService.java @@ -1,8 +1,7 @@ package wooteco.chess.service; -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; @@ -11,37 +10,33 @@ import wooteco.chess.dto.PiecesResponseDTO; import java.sql.SQLException; -import java.util.Collection; import java.util.List; -@Service -public class GameService { - private static final GameService GAME_SERVICE = new GameService(); +public class SparkGameService { + private static final SparkGameService GAME_SERVICE = new SparkGameService(); - private GameService() { + private SparkGameService() { } - public static GameService getInstance() { + public static SparkGameService getInstance() { return GAME_SERVICE; } - public GameManagerDTO initialize(int roomId) throws SQLException { - GameDAO gameDAO = GameDAO.getInstance(); - RoomDAO roomDAO = RoomDAO.getInstance(); + public void initialize(int roomId) throws SQLException { + SparkGameDAO gameDAO = SparkGameDAO.getInstance(); + SparkRoomDAO roomDAO = SparkRoomDAO.getInstance(); 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 { - GameDAO gameDAO = GameDAO.getInstance(); - RoomDAO roomDAO = RoomDAO.getInstance(); + 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()); @@ -50,7 +45,7 @@ public void movePiece(int roomId, String sourcePosition, String targetPosition) } public double getScore(int roomId, Color color) throws SQLException { - GameDAO gameDAO = GameDAO.getInstance(); + SparkGameDAO gameDAO = SparkGameDAO.getInstance(); Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); GameManager gameManager = new GameManager(pieces, color); @@ -58,14 +53,14 @@ public double getScore(int roomId, Color color) throws SQLException { } public PiecesResponseDTO getPiecesResponseDTO(int roomId) throws SQLException { - GameDAO gameDAO = GameDAO.getInstance(); + SparkGameDAO gameDAO = SparkGameDAO.getInstance(); Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); return new PiecesResponseDTO(pieces); } public boolean isKingDead(final int roomId) throws SQLException { - GameDAO gameDAO = GameDAO.getInstance(); - RoomDAO roomDAO = RoomDAO.getInstance(); + SparkGameDAO gameDAO = SparkGameDAO.getInstance(); + SparkRoomDAO roomDAO = SparkRoomDAO.getInstance(); Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); GameManager gameManager = new GameManager(pieces, roomDAO.findRoomColorById(roomId)); @@ -73,13 +68,13 @@ public boolean isKingDead(final int roomId) throws SQLException { } public String getCurrentColor(final int roomId) throws SQLException { - RoomDAO roomDAO = RoomDAO.getInstance(); + SparkRoomDAO roomDAO = SparkRoomDAO.getInstance(); return roomDAO.findRoomColorById(roomId).name(); } public List getMovablePositions(final int roomId, final String sourcePosition) throws SQLException { - GameDAO gameDAO = GameDAO.getInstance(); - RoomDAO roomDAO = RoomDAO.getInstance(); + SparkGameDAO gameDAO = SparkGameDAO.getInstance(); + SparkRoomDAO roomDAO = SparkRoomDAO.getInstance(); Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); GameManager gameManager = new GameManager(pieces, roomDAO.findRoomColorById(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/SpringRoomService.java b/src/main/java/wooteco/chess/service/SpringRoomService.java new file mode 100644 index 0000000000..3cf2f4963d --- /dev/null +++ b/src/main/java/wooteco/chess/service/SpringRoomService.java @@ -0,0 +1,29 @@ +package wooteco.chess.service; + +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 SpringRoomService { + + @Autowired + private RoomDAO roomDAO; + + public void addRoom(String roomName) throws SQLException { + roomDAO.addRoom(roomName, Color.WHITE.name()); + } + + public void removeRoom(int roomId) throws SQLException { + roomDAO.removeRoomById(roomId); + } + + public List findAllRoom() throws SQLException { + return roomDAO.findAllRoom(); + } +} diff --git a/src/main/java/wooteco/chess/controller/SparkGameController.java b/src/main/java/wooteco/chess/sparkcontroller/SparkGameController.java similarity index 85% rename from src/main/java/wooteco/chess/controller/SparkGameController.java rename to src/main/java/wooteco/chess/sparkcontroller/SparkGameController.java index eeb3794d29..87d98a5ef2 100644 --- a/src/main/java/wooteco/chess/controller/SparkGameController.java +++ b/src/main/java/wooteco/chess/sparkcontroller/SparkGameController.java @@ -1,11 +1,11 @@ -package wooteco.chess.controller; +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.GameService; +import wooteco.chess.service.SparkGameService; import java.sql.SQLException; @@ -18,7 +18,7 @@ public class SparkGameController { public static final String GET_URL = BASIC_URL + "/get"; public static String initGame(Request request, Response response) throws SQLException { - GameService gameService = GameService.getInstance(); + SparkGameService gameService = SparkGameService.getInstance(); int roomId = Integer.parseInt(request.queryParams("roomId")); gameService.initialize(roomId); @@ -34,7 +34,7 @@ public static String initGame(Request request, Response response) throws SQLExce } public static String movePiece(Request request, Response response) throws SQLException { - GameService gameService = GameService.getInstance(); + SparkGameService gameService = SparkGameService.getInstance(); int roomId = Integer.parseInt(request.queryParams("roomId")); String sourcePosition = request.queryParams("sourcePosition"); @@ -55,7 +55,7 @@ public static String movePiece(Request request, Response response) throws SQLExc } public static String showStatus(Request request, Response response) throws SQLException { - GameService gameService = GameService.getInstance(); + SparkGameService gameService = SparkGameService.getInstance(); int roomId = Integer.parseInt(request.queryParams("roomId")); double whiteScore = gameService.getScore(roomId, Color.WHITE); @@ -71,7 +71,7 @@ public static String showStatus(Request request, Response response) throws SQLEx } public static String loadGame(Request request, Response response) throws SQLException { - GameService gameService = GameService.getInstance(); + SparkGameService gameService = SparkGameService.getInstance(); int roomId = Integer.parseInt(request.queryParams("roomId")); Gson gson = new Gson(); @@ -85,8 +85,8 @@ public static String loadGame(Request request, Response response) throws SQLExce return gson.toJson(object); } - public static String getMovablePositions(final Request request, final Response response) throws SQLException { - GameService gameService = GameService.getInstance(); + 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"); diff --git a/src/main/java/wooteco/chess/controller/SparkRoomController.java b/src/main/java/wooteco/chess/sparkcontroller/SparkRoomController.java similarity index 77% rename from src/main/java/wooteco/chess/controller/SparkRoomController.java rename to src/main/java/wooteco/chess/sparkcontroller/SparkRoomController.java index ff0f1ebca9..cc21a2e285 100644 --- a/src/main/java/wooteco/chess/controller/SparkRoomController.java +++ b/src/main/java/wooteco/chess/sparkcontroller/SparkRoomController.java @@ -1,8 +1,8 @@ -package wooteco.chess.controller; +package wooteco.chess.sparkcontroller; -import wooteco.chess.domain.room.Room; -import wooteco.chess.service.RoomService; import spark.Route; +import wooteco.chess.domain.room.Room; +import wooteco.chess.service.SparkRoomService; import java.util.HashMap; import java.util.List; @@ -19,30 +19,31 @@ public class SparkRoomController { public static Route getAllRoom = (request, response) -> { Map model = new HashMap<>(); - RoomService roomService = RoomService.getInstance(); + SparkRoomService roomService = SparkRoomService.getInstance(); List rooms = roomService.findAllRoom(); model.put("rooms", rooms); - return render(model, "index.hbs"); + 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.hbs"); + return render(model, "game.html"); }; public static Route createRoom = (request, response) -> { - RoomService roomService = RoomService.getInstance(); + SparkRoomService roomService = SparkRoomService.getInstance(); String param = request.queryParams("roomName"); roomService.addRoom(param); response.redirect("/rooms"); return null; }; + public static Route removeRoom = (request, response) -> { - RoomService roomService = RoomService.getInstance(); + SparkRoomService roomService = SparkRoomService.getInstance(); roomService.removeRoom(Integer.parseInt(request.queryParams("roomId"))); response.redirect("/rooms"); diff --git a/src/main/java/wooteco/chess/util/JDBCConnector.java b/src/main/java/wooteco/chess/util/JDBCConnector.java index ceda8892eb..9933909e27 100644 --- a/src/main/java/wooteco/chess/util/JDBCConnector.java +++ b/src/main/java/wooteco/chess/util/JDBCConnector.java @@ -30,14 +30,4 @@ public static Connection getConnection() { } return con; } - - public static void closeConnection(Connection con) { - try { - if (con != null) { - con.close(); - } - } catch (SQLException e) { - System.err.println("con 오류 : " + e.getMessage()); - } - } } diff --git a/src/main/java/wooteco/chess/view/InputView.java b/src/main/java/wooteco/chess/view/InputView.java deleted file mode 100644 index 72f82461ad..0000000000 --- a/src/main/java/wooteco/chess/view/InputView.java +++ /dev/null @@ -1,25 +0,0 @@ -package wooteco.chess.view; - -import java.util.Scanner; - -/** - * @author AnHyungJu, LeeHoBin - */ -public class InputView { - private static final Scanner scanner = new Scanner(System.in); - - private InputView() { - } - - public static String inputCommand() { - try { - System.out.println("명령을 입력해주세요."); - return scanner.nextLine(); - } catch (IllegalArgumentException e) { - OutputView.printException(e); - return inputCommand(); - } - } - - -} diff --git a/src/main/java/wooteco/chess/view/OutputView.java b/src/main/java/wooteco/chess/view/OutputView.java deleted file mode 100644 index 2d5ca46bc6..0000000000 --- a/src/main/java/wooteco/chess/view/OutputView.java +++ /dev/null @@ -1,52 +0,0 @@ -package wooteco.chess.view; - -import wooteco.chess.domain.Color; -import wooteco.chess.domain.GameManager; -import wooteco.chess.domain.PieceScore; -import wooteco.chess.domain.board.Column; -import wooteco.chess.domain.board.Position; -import wooteco.chess.domain.board.Row; - -/** - * @author AnHyungJu, LeeHoBin - */ -public class OutputView { - public static final String BLANK_POSITION = "."; - - private OutputView() { - } - - public static void printGameInstruction() { - System.out.println("체스 게임을 시작합니다."); - System.out.println("게임 시작: start"); - System.out.println("게임 종료: end"); - System.out.println("게임 이동: move source위치 target위치 - 예. move b2 b3"); - } - - public static void printException(Exception e) { - System.out.println(e.getMessage()); - } - - public static void printGameEnd() { - System.out.println("게임을 종료합니다."); - } - - public static void printChessBoard(GameManager gameManager) { - for (Row row : Row.values()) { - for (Column column : Column.values()) { - Position position = Position.of(column, row); - if (gameManager.getPiece(column.getColumn() + row.getRow()).isBlank()) { - System.out.print(BLANK_POSITION); - continue; - } - System.out.print(gameManager.getPiece(column.getColumn() + row.getRow()).getSymbol()); - } - System.out.println(); - } - } - - public static void printStatus(GameManager gameManager) { - System.out.println("하얀색 진영의 점수 : " + PieceScore.calculateByColor(gameManager, Color.WHITE)); - System.out.println("검정색 진영의 점수 : " + PieceScore.calculateByColor(gameManager, Color.BLACK)); - } -} 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 c53646851b..3383d6b83e 100644 --- a/src/main/resources/templates/game.hbs +++ b/src/main/resources/templates/game.hbs @@ -141,13 +141,9 @@ let allChessPosition = document.querySelectorAll(".chessPosition"); let isChooseSourcePosition = false; let loadable = false; - let helloworld; - let sourcePosition; let movablePositions; - window.onload = function () { - function applyMovablePosition(movablePositions) { movablePositions.forEach(function (movablePosition) { addBorder(movablePosition); @@ -241,7 +237,6 @@ document.getElementById("initButton").addEventListener('click', function () { init(); }); - document.getElementById("statusButton").addEventListener('click', function () { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { @@ -254,12 +249,14 @@ xhr.send(); }); - function move(sourcePosition, targetPosition) { + function move(source, target) { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { let chessJson = JSON.parse(xhr.responseText); - if (typeof chessJson.errorMessage == "undefined") { + console.log(chessJson); + console.log(chessJson.pieces); + if (chessJson.errorMessage == null) { applyPieces(chessJson.pieces); let currentColor = chessJson.currentColor; isKingDead(currentColor, chessJson.kingDead); @@ -269,12 +266,14 @@ } } }; - 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++) { @@ -283,10 +282,8 @@ sourcePosition = allChessPosition[i].id; getMovablePosition(sourcePosition); } - }); } - for (let i = 0; i < allChessPosition.length; i++) { allChessPosition[i].addEventListener('click', function () { if (isChooseSourcePosition) { @@ -297,7 +294,6 @@ } }); } - document.getElementById("overlay").addEventListener('click', function () { removeBlur(); removeOverlay(); @@ -308,17 +304,17 @@ xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { let chessJson = JSON.parse(xhr.responseText); - let pieces = JSON.parse(chessJson.pieces); - if(pieces.length === 64) { + let pieces = chessJson.pieces; + if (pieces.length === 64) { let isLoad = confirm("저장된 게임이 이미 있습니다! 불러올까요?"); - if(isLoad) { + if (isLoad) { applyPieces(pieces); showCurrentColor(chessJson.currentColor); alert("정상적으로 불러왔습니다!"); } else { init(); } - }else { + } else { init(); } } @@ -340,9 +336,9 @@ xhr.open('GET', '/game/init?roomId={{roomId}}', true); xhr.send(); } + load(); } - - \ No newline at end of file + 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(); + } } From e1d312692f6814ba12a004ea4d7b0e9083d94063 Mon Sep 17 00:00:00 2001 From: dd Date: Mon, 27 Apr 2020 17:08:09 +0900 Subject: [PATCH 03/10] =?UTF-8?q?refactor=20:=20RoomDAO=20=EB=A5=BC=20spri?= =?UTF-8?q?ng=20data=20jdbc=20repository=EB=A1=9C=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../wooteco/chess/SparkChessApplication.java | 35 ---- .../controller/SpringGameController.java | 19 +- .../controller/SpringRoomController.java | 4 +- src/main/java/wooteco/chess/dao/RoomDAO.java | 118 ------------- .../java/wooteco/chess/dao/SparkGameDAO.java | 157 ----------------- .../java/wooteco/chess/dao/SparkRoomDAO.java | 166 ------------------ .../chess/domain/piece/PieceMapper.java | 6 +- .../java/wooteco/chess/domain/room/Room.java | 25 --- ...ameManagerDTO.java => GameManagerDto.java} | 10 +- ...{GameStatusDTO.java => GameStatusDto.java} | 4 +- ...sitionDTO.java => MovablePositionDto.java} | 4 +- ...ePositionDTO.java => MovePositionDto.java} | 4 +- ...oveRequestDTO.java => MoveRequestDto.java} | 4 +- ...eResponseDTO.java => MoveResponseDto.java} | 8 +- ...ResponseDTO.java => PieceResponseDto.java} | 4 +- ...esponseDTO.java => PiecesResponseDto.java} | 8 +- .../wooteco/chess/dto/RoomResponseDto.java | 31 ++++ .../chess/{dao => repository}/GameDAO.java | 2 +- .../{dao => repository}/JdbcTemplate.java | 2 +- .../PreparedStatementSetter.java | 2 +- .../chess/repository/RoomRepository.java | 16 ++ .../chess/{dao => repository}/RowMapper.java | 2 +- .../chess/repository/entity/RoomEntity.java | 46 +++++ .../chess/service/SparkGameService.java | 84 --------- .../chess/service/SparkRoomService.java | 31 ---- .../chess/service/SpringGameService.java | 58 +++--- .../chess/service/SpringRoomService.java | 20 ++- .../sparkcontroller/SparkGameController.java | 97 ---------- .../sparkcontroller/SparkRoomController.java | 55 ------ src/main/resources/templates/game.hbs | 2 +- src/main/resources/templates/index.html | 10 +- 31 files changed, 189 insertions(+), 845 deletions(-) delete mode 100644 src/main/java/wooteco/chess/SparkChessApplication.java delete mode 100644 src/main/java/wooteco/chess/dao/RoomDAO.java delete mode 100644 src/main/java/wooteco/chess/dao/SparkGameDAO.java delete mode 100644 src/main/java/wooteco/chess/dao/SparkRoomDAO.java delete mode 100644 src/main/java/wooteco/chess/domain/room/Room.java rename src/main/java/wooteco/chess/dto/{GameManagerDTO.java => GameManagerDto.java} (73%) rename src/main/java/wooteco/chess/dto/{GameStatusDTO.java => GameStatusDto.java} (78%) rename src/main/java/wooteco/chess/dto/{MovablePositionDTO.java => MovablePositionDto.java} (68%) rename src/main/java/wooteco/chess/dto/{MovePositionDTO.java => MovePositionDto.java} (80%) rename src/main/java/wooteco/chess/dto/{MoveRequestDTO.java => MoveRequestDto.java} (84%) rename src/main/java/wooteco/chess/dto/{MoveResponseDTO.java => MoveResponseDto.java} (78%) rename src/main/java/wooteco/chess/dto/{PieceResponseDTO.java => PieceResponseDto.java} (75%) rename src/main/java/wooteco/chess/dto/{PiecesResponseDTO.java => PiecesResponseDto.java} (59%) create mode 100644 src/main/java/wooteco/chess/dto/RoomResponseDto.java rename src/main/java/wooteco/chess/{dao => repository}/GameDAO.java (99%) rename src/main/java/wooteco/chess/{dao => repository}/JdbcTemplate.java (97%) rename src/main/java/wooteco/chess/{dao => repository}/PreparedStatementSetter.java (84%) create mode 100644 src/main/java/wooteco/chess/repository/RoomRepository.java rename src/main/java/wooteco/chess/{dao => repository}/RowMapper.java (81%) create mode 100644 src/main/java/wooteco/chess/repository/entity/RoomEntity.java delete mode 100644 src/main/java/wooteco/chess/service/SparkGameService.java delete mode 100644 src/main/java/wooteco/chess/service/SparkRoomService.java delete mode 100644 src/main/java/wooteco/chess/sparkcontroller/SparkGameController.java delete mode 100644 src/main/java/wooteco/chess/sparkcontroller/SparkRoomController.java diff --git a/src/main/java/wooteco/chess/SparkChessApplication.java b/src/main/java/wooteco/chess/SparkChessApplication.java deleted file mode 100644 index a5ed5c8780..0000000000 --- a/src/main/java/wooteco/chess/SparkChessApplication.java +++ /dev/null @@ -1,35 +0,0 @@ -package wooteco.chess; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import wooteco.chess.sparkcontroller.SparkGameController; -import wooteco.chess.sparkcontroller.SparkRoomController; - -import static spark.Spark.*; - -public class SparkChessApplication { - public static void main(String[] args) { - port(4567); - 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)); - }); - } -} diff --git a/src/main/java/wooteco/chess/controller/SpringGameController.java b/src/main/java/wooteco/chess/controller/SpringGameController.java index ececae641c..9e4c4a5c98 100644 --- a/src/main/java/wooteco/chess/controller/SpringGameController.java +++ b/src/main/java/wooteco/chess/controller/SpringGameController.java @@ -1,13 +1,12 @@ package wooteco.chess.controller; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import wooteco.chess.domain.Color; -import wooteco.chess.dto.MoveResponseDTO; -import wooteco.chess.dto.GameStatusDTO; -import wooteco.chess.dto.MoveRequestDTO; +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; @@ -25,28 +24,28 @@ public SpringGameController(final SpringGameService gameService) { } @GetMapping("/init") - public MoveResponseDTO init(@RequestParam Integer roomId) throws SQLException { + public MoveResponseDto init(@RequestParam Integer roomId) throws SQLException { return gameService.initialize(roomId); } @PostMapping("/move") - public ResponseEntity move(@RequestBody MoveRequestDTO requestDTO) throws SQLException { + public ResponseEntity move(@RequestBody MoveRequestDto requestDTO) throws SQLException { try { return ResponseEntity.status(HttpStatus.OK).body(gameService.move(requestDTO)); } catch (IllegalArgumentException e) { - MoveResponseDTO moveResponseDTO = gameService.createMoveResponseDTO(requestDTO.getRoomId()); + MoveResponseDto moveResponseDTO = gameService.createMoveResponseDTO(requestDTO.getRoomId()); moveResponseDTO.setErrorMessage(e.getMessage()); return ResponseEntity.status(HttpStatus.OK).body(moveResponseDTO); } } @GetMapping("/status") - public GameStatusDTO showStatus(@RequestParam Integer roomId) throws SQLException { - return new GameStatusDTO(gameService.getScore(roomId, Color.WHITE), gameService.getScore(roomId, Color.BLACK)); + public GameStatusDto showStatus(@RequestParam Integer roomId) throws SQLException { + return new GameStatusDto(gameService.getScore(roomId, Color.WHITE), gameService.getScore(roomId, Color.BLACK)); } @GetMapping("/load") - public MoveResponseDTO load(@RequestParam Integer roomId) throws SQLException { + public MoveResponseDto load(@RequestParam Integer roomId) throws SQLException { return gameService.createMoveResponseDTO(roomId); } diff --git a/src/main/java/wooteco/chess/controller/SpringRoomController.java b/src/main/java/wooteco/chess/controller/SpringRoomController.java index f0a25bc602..dcdf70153e 100644 --- a/src/main/java/wooteco/chess/controller/SpringRoomController.java +++ b/src/main/java/wooteco/chess/controller/SpringRoomController.java @@ -6,7 +6,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; -import wooteco.chess.domain.room.Room; +import wooteco.chess.dto.RoomResponseDto; import wooteco.chess.dto.RoomName; import wooteco.chess.service.SpringRoomService; @@ -26,7 +26,7 @@ private SpringRoomController(final SpringRoomService roomService) { @GetMapping public String getAllRooms(Model model) throws SQLException { - List rooms = roomService.findAllRoom(); + List rooms = roomService.findAllRoom(); model.addAttribute("rooms", rooms); return "index"; diff --git a/src/main/java/wooteco/chess/dao/RoomDAO.java b/src/main/java/wooteco/chess/dao/RoomDAO.java deleted file mode 100644 index 4377c14b7c..0000000000 --- a/src/main/java/wooteco/chess/dao/RoomDAO.java +++ /dev/null @@ -1,118 +0,0 @@ -package wooteco.chess.dao; - -import org.springframework.stereotype.Repository; -import wooteco.chess.domain.Color; -import wooteco.chess.domain.room.Room; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -@Repository -public class RoomDAO { - public void addRoom(String roomName, String roomColor) throws SQLException { - String query = "INSERT INTO room(room_name, room_color) VALUES (?, ?)"; - - PreparedStatementSetter pss = pstmt -> { - 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 = pstmt -> 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 = pstmt -> { - 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 = pstmt -> pstmt.setInt(1, roomId); - - RowMapper rm = rs -> { - 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 = pstmt -> pstmt.setString(1, roomName); - - RowMapper rm = rs -> { - 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 = pstmt -> { - }; - - RowMapper rm = rs -> { - 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 = pstmt -> pstmt.setInt(1, roomId); - - RowMapper rm = rs -> { - 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/dao/SparkGameDAO.java b/src/main/java/wooteco/chess/dao/SparkGameDAO.java deleted file mode 100644 index 75b5499c9d..0000000000 --- a/src/main/java/wooteco/chess/dao/SparkGameDAO.java +++ /dev/null @@ -1,157 +0,0 @@ -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 deleted file mode 100644 index 887cd16a97..0000000000 --- a/src/main/java/wooteco/chess/dao/SparkRoomDAO.java +++ /dev/null @@ -1,166 +0,0 @@ -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/piece/PieceMapper.java b/src/main/java/wooteco/chess/domain/piece/PieceMapper.java index f052e77b99..244b1cd663 100644 --- a/src/main/java/wooteco/chess/domain/piece/PieceMapper.java +++ b/src/main/java/wooteco/chess/domain/piece/PieceMapper.java @@ -1,7 +1,7 @@ package wooteco.chess.domain.piece; import wooteco.chess.domain.Color; -import wooteco.chess.dto.PieceResponseDTO; +import wooteco.chess.dto.PieceResponseDto; import java.util.HashMap; import java.util.List; @@ -60,9 +60,9 @@ public String findViewPiece(String pieceSymbol) { return pieceViewMapper.get(pieceSymbol); } - public List createPiecesResponseDTO(Pieces pieces) { + public List createPiecesResponseDTO(Pieces pieces) { return pieces.getPieces().keySet().stream() - .map(position -> new PieceResponseDTO( + .map(position -> new PieceResponseDto( position.getPosition(), findViewPiece(pieces.getPieceByPosition(position).getSymbol())) ) diff --git a/src/main/java/wooteco/chess/domain/room/Room.java b/src/main/java/wooteco/chess/domain/room/Room.java deleted file mode 100644 index e0c0a80a0e..0000000000 --- a/src/main/java/wooteco/chess/domain/room/Room.java +++ /dev/null @@ -1,25 +0,0 @@ -package wooteco.chess.domain.room; - -public class Room { - private final int roomId; - private final String roomName; - private final String turn; - - public Room(int roomId, String roomName, String turn) { - this.roomId = roomId; - this.roomName = roomName; - this.turn = turn; - } - - public int getRoomId() { - return roomId; - } - - public String getRoomName() { - return roomName; - } - - public String getTurn() { - return turn; - } -} diff --git a/src/main/java/wooteco/chess/dto/GameManagerDTO.java b/src/main/java/wooteco/chess/dto/GameManagerDto.java similarity index 73% rename from src/main/java/wooteco/chess/dto/GameManagerDTO.java rename to src/main/java/wooteco/chess/dto/GameManagerDto.java index 35172d5ce6..0b879334f6 100644 --- a/src/main/java/wooteco/chess/dto/GameManagerDTO.java +++ b/src/main/java/wooteco/chess/dto/GameManagerDto.java @@ -1,24 +1,22 @@ package wooteco.chess.dto; import wooteco.chess.domain.Color; -import wooteco.chess.dto.PieceResponseDTO; import java.util.List; -import java.util.Map; -public class GameManagerDTO { - private final List pieces; +public class GameManagerDto { + private final List pieces; private final Color currentColor; private final boolean kingDead; private String errorMessage; - public GameManagerDTO(final List pieces, final Color currentColor, final boolean kingDead) { + public GameManagerDto(final List pieces, final Color currentColor, final boolean kingDead) { this.pieces = pieces; this.currentColor = currentColor; this.kingDead = kingDead; } - public List getPieces() { + public List getPieces() { return pieces; } diff --git a/src/main/java/wooteco/chess/dto/GameStatusDTO.java b/src/main/java/wooteco/chess/dto/GameStatusDto.java similarity index 78% rename from src/main/java/wooteco/chess/dto/GameStatusDTO.java rename to src/main/java/wooteco/chess/dto/GameStatusDto.java index 18774c5cda..19986297b9 100644 --- a/src/main/java/wooteco/chess/dto/GameStatusDTO.java +++ b/src/main/java/wooteco/chess/dto/GameStatusDto.java @@ -1,10 +1,10 @@ package wooteco.chess.dto; -public class GameStatusDTO { +public class GameStatusDto { private final double whiteScore; private final double blackScore; - public GameStatusDTO(final double whiteScore, final double blackScore) { + public GameStatusDto(final double whiteScore, final double blackScore) { this.whiteScore = whiteScore; this.blackScore = blackScore; } diff --git a/src/main/java/wooteco/chess/dto/MovablePositionDTO.java b/src/main/java/wooteco/chess/dto/MovablePositionDto.java similarity index 68% rename from src/main/java/wooteco/chess/dto/MovablePositionDTO.java rename to src/main/java/wooteco/chess/dto/MovablePositionDto.java index 9c3fe0a9e4..5e51d2e894 100644 --- a/src/main/java/wooteco/chess/dto/MovablePositionDTO.java +++ b/src/main/java/wooteco/chess/dto/MovablePositionDto.java @@ -2,10 +2,10 @@ import java.util.List; -public class MovablePositionDTO { +public class MovablePositionDto { private final List positions; - public MovablePositionDTO(final List positions) { + public MovablePositionDto(final List positions) { this.positions = positions; } diff --git a/src/main/java/wooteco/chess/dto/MovePositionDTO.java b/src/main/java/wooteco/chess/dto/MovePositionDto.java similarity index 80% rename from src/main/java/wooteco/chess/dto/MovePositionDTO.java rename to src/main/java/wooteco/chess/dto/MovePositionDto.java index cd53f20b55..10c8bafb21 100644 --- a/src/main/java/wooteco/chess/dto/MovePositionDTO.java +++ b/src/main/java/wooteco/chess/dto/MovePositionDto.java @@ -1,10 +1,10 @@ package wooteco.chess.dto; -public class MovePositionDTO { +public class MovePositionDto { private final String sourcePosition; private final String targetPosition; - public MovePositionDTO(final String sourcePosition, final String targetPosition) { + public MovePositionDto(final String sourcePosition, final String targetPosition) { this.sourcePosition = sourcePosition; this.targetPosition = targetPosition; } diff --git a/src/main/java/wooteco/chess/dto/MoveRequestDTO.java b/src/main/java/wooteco/chess/dto/MoveRequestDto.java similarity index 84% rename from src/main/java/wooteco/chess/dto/MoveRequestDTO.java rename to src/main/java/wooteco/chess/dto/MoveRequestDto.java index a796d3487b..ed738e24f2 100644 --- a/src/main/java/wooteco/chess/dto/MoveRequestDTO.java +++ b/src/main/java/wooteco/chess/dto/MoveRequestDto.java @@ -1,12 +1,12 @@ package wooteco.chess.dto; -public class MoveRequestDTO { +public class MoveRequestDto { private Integer roomId; private String sourcePosition; private String targetPosition; - public MoveRequestDTO(final Integer roomId, final String sourcePosition, final String targetPosition) { + public MoveRequestDto(final Integer roomId, final String sourcePosition, final String targetPosition) { this.roomId = roomId; this.sourcePosition = sourcePosition; this.targetPosition = targetPosition; diff --git a/src/main/java/wooteco/chess/dto/MoveResponseDTO.java b/src/main/java/wooteco/chess/dto/MoveResponseDto.java similarity index 78% rename from src/main/java/wooteco/chess/dto/MoveResponseDTO.java rename to src/main/java/wooteco/chess/dto/MoveResponseDto.java index bca29fa903..06e57cd7c3 100644 --- a/src/main/java/wooteco/chess/dto/MoveResponseDTO.java +++ b/src/main/java/wooteco/chess/dto/MoveResponseDto.java @@ -4,19 +4,19 @@ import java.util.List; -public class MoveResponseDTO { - private final List pieces; +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) { + public MoveResponseDto(final List pieces, final Color currentColor, final boolean kingDead) { this.pieces = pieces; this.currentColor = currentColor; this.kingDead = kingDead; } - public List getPieces() { + public List getPieces() { return pieces; } diff --git a/src/main/java/wooteco/chess/dto/PieceResponseDTO.java b/src/main/java/wooteco/chess/dto/PieceResponseDto.java similarity index 75% rename from src/main/java/wooteco/chess/dto/PieceResponseDTO.java rename to src/main/java/wooteco/chess/dto/PieceResponseDto.java index 52dc10e62c..394a0a3c5b 100644 --- a/src/main/java/wooteco/chess/dto/PieceResponseDTO.java +++ b/src/main/java/wooteco/chess/dto/PieceResponseDto.java @@ -1,10 +1,10 @@ package wooteco.chess.dto; -public class PieceResponseDTO { +public class PieceResponseDto { private final String position; private final String imgUrl; - public PieceResponseDTO(String position, String imgUrl) { + public PieceResponseDto(String position, String imgUrl) { this.position = position; this.imgUrl = imgUrl; } diff --git a/src/main/java/wooteco/chess/dto/PiecesResponseDTO.java b/src/main/java/wooteco/chess/dto/PiecesResponseDto.java similarity index 59% rename from src/main/java/wooteco/chess/dto/PiecesResponseDTO.java rename to src/main/java/wooteco/chess/dto/PiecesResponseDto.java index 2efd240b85..3058b6c2d3 100644 --- a/src/main/java/wooteco/chess/dto/PiecesResponseDTO.java +++ b/src/main/java/wooteco/chess/dto/PiecesResponseDto.java @@ -5,14 +5,14 @@ import java.util.List; -public class PiecesResponseDTO { - private final List pieces; +public class PiecesResponseDto { + private final List pieces; - public PiecesResponseDTO(Pieces originPieces) { + public PiecesResponseDto(Pieces originPieces) { this.pieces = PieceMapper.getInstance().createPiecesResponseDTO(originPieces); } - public List getPieces() { + public List getPieces() { return pieces; } } diff --git a/src/main/java/wooteco/chess/dto/RoomResponseDto.java b/src/main/java/wooteco/chess/dto/RoomResponseDto.java new file mode 100644 index 0000000000..95a4fcec09 --- /dev/null +++ b/src/main/java/wooteco/chess/dto/RoomResponseDto.java @@ -0,0 +1,31 @@ +package wooteco.chess.dto; + +import wooteco.chess.repository.entity.RoomEntity; + +public class RoomResponseDto { + private final int roomId; + private final String roomName; + private final String currentColor; + + private RoomResponseDto(int roomId, String roomName, String currentColor) { + this.roomId = roomId; + this.roomName = roomName; + this.currentColor = currentColor; + } + + public static RoomResponseDto of(RoomEntity roomEntity) { + return new RoomResponseDto(roomEntity.getRoomId(), roomEntity.getRoomName(), roomEntity.getCurrentColor()); + } + + public int getRoomId() { + return roomId; + } + + public String getRoomName() { + return roomName; + } + + public String getCurrentColor() { + return currentColor; + } +} diff --git a/src/main/java/wooteco/chess/dao/GameDAO.java b/src/main/java/wooteco/chess/repository/GameDAO.java similarity index 99% rename from src/main/java/wooteco/chess/dao/GameDAO.java rename to src/main/java/wooteco/chess/repository/GameDAO.java index 7b6dcd250b..aab2396eb5 100644 --- a/src/main/java/wooteco/chess/dao/GameDAO.java +++ b/src/main/java/wooteco/chess/repository/GameDAO.java @@ -1,4 +1,4 @@ -package wooteco.chess.dao; +package wooteco.chess.repository; import org.springframework.stereotype.Repository; import wooteco.chess.domain.board.Position; diff --git a/src/main/java/wooteco/chess/dao/JdbcTemplate.java b/src/main/java/wooteco/chess/repository/JdbcTemplate.java similarity index 97% rename from src/main/java/wooteco/chess/dao/JdbcTemplate.java rename to src/main/java/wooteco/chess/repository/JdbcTemplate.java index 470e55b6ed..fef402bfd5 100644 --- a/src/main/java/wooteco/chess/dao/JdbcTemplate.java +++ b/src/main/java/wooteco/chess/repository/JdbcTemplate.java @@ -1,4 +1,4 @@ -package wooteco.chess.dao; +package wooteco.chess.repository; import wooteco.chess.util.JDBCConnector; diff --git a/src/main/java/wooteco/chess/dao/PreparedStatementSetter.java b/src/main/java/wooteco/chess/repository/PreparedStatementSetter.java similarity index 84% rename from src/main/java/wooteco/chess/dao/PreparedStatementSetter.java rename to src/main/java/wooteco/chess/repository/PreparedStatementSetter.java index b57cfe0c7d..af2b11d862 100644 --- a/src/main/java/wooteco/chess/dao/PreparedStatementSetter.java +++ b/src/main/java/wooteco/chess/repository/PreparedStatementSetter.java @@ -1,4 +1,4 @@ -package wooteco.chess.dao; +package wooteco.chess.repository; import java.sql.PreparedStatement; import java.sql.SQLException; diff --git a/src/main/java/wooteco/chess/repository/RoomRepository.java b/src/main/java/wooteco/chess/repository/RoomRepository.java new file mode 100644 index 0000000000..19b23ede73 --- /dev/null +++ b/src/main/java/wooteco/chess/repository/RoomRepository.java @@ -0,0 +1,16 @@ +package wooteco.chess.repository; + +import org.springframework.data.jdbc.repository.query.Modifying; +import org.springframework.data.jdbc.repository.query.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; +import wooteco.chess.domain.Color; +import wooteco.chess.repository.entity.RoomEntity; + +public interface RoomRepository extends CrudRepository { + + @Modifying + @Query("UPDATE room SET room_color = :currentColor WHERE room_id = :roomId") + void updateRoomColorById(int roomId, String currentColor); + +} diff --git a/src/main/java/wooteco/chess/dao/RowMapper.java b/src/main/java/wooteco/chess/repository/RowMapper.java similarity index 81% rename from src/main/java/wooteco/chess/dao/RowMapper.java rename to src/main/java/wooteco/chess/repository/RowMapper.java index e55741c2cb..6cbb3d7f5c 100644 --- a/src/main/java/wooteco/chess/dao/RowMapper.java +++ b/src/main/java/wooteco/chess/repository/RowMapper.java @@ -1,4 +1,4 @@ -package wooteco.chess.dao; +package wooteco.chess.repository; import java.sql.ResultSet; import java.sql.SQLException; diff --git a/src/main/java/wooteco/chess/repository/entity/RoomEntity.java b/src/main/java/wooteco/chess/repository/entity/RoomEntity.java new file mode 100644 index 0000000000..1f847fd7ab --- /dev/null +++ b/src/main/java/wooteco/chess/repository/entity/RoomEntity.java @@ -0,0 +1,46 @@ +package wooteco.chess.repository.entity; + +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.PersistenceConstructor; +import org.springframework.data.relational.core.mapping.Column; +import org.springframework.data.relational.core.mapping.Table; +import wooteco.chess.domain.Color; + +@Table("room") +public class RoomEntity { + + @Id + private Integer roomId; + + private String roomName; + + @Column("room_color") + private String currentColor; + + + private RoomEntity(){ + } + + public RoomEntity(final String roomName, final String currentColor) { + this.roomName = roomName; + this.currentColor = currentColor; + } + + public RoomEntity(final int roomId, final String roomName, final String currentColor) { + this.roomId = roomId; + this.roomName = roomName; + this.currentColor = currentColor; + } + + public int getRoomId() { + return roomId; + } + + public String getRoomName() { + return roomName; + } + + public String getCurrentColor() { + return currentColor; + } +} diff --git a/src/main/java/wooteco/chess/service/SparkGameService.java b/src/main/java/wooteco/chess/service/SparkGameService.java deleted file mode 100644 index d3a5907c52..0000000000 --- a/src/main/java/wooteco/chess/service/SparkGameService.java +++ /dev/null @@ -1,84 +0,0 @@ -package wooteco.chess.service; - -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.PiecesResponseDTO; - -import java.sql.SQLException; -import java.util.List; - -public class SparkGameService { - private static final SparkGameService GAME_SERVICE = new SparkGameService(); - - private SparkGameService() { - } - - public static SparkGameService getInstance() { - return GAME_SERVICE; - } - - public void initialize(int roomId) throws SQLException { - SparkGameDAO gameDAO = SparkGameDAO.getInstance(); - SparkRoomDAO roomDAO = SparkRoomDAO.getInstance(); - - roomDAO.updateRoomColorById(roomId, Color.WHITE); - Pieces pieces = new Pieces(Pieces.initPieces()); - gameDAO.addAllPiecesById(roomId, pieces); - } - - 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.moveFromTo(Position.of(sourcePosition), Position.of(targetPosition)); - roomDAO.updateRoomColorById(roomId, gameManager.getCurrentColor()); - - gameDAO.removeAllPiecesById(roomId); - gameDAO.addAllPiecesById(roomId, pieces); - } - - 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); - - return PieceScore.calculateByColor(gameManager, color); - } - - 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)); - } -} diff --git a/src/main/java/wooteco/chess/service/SparkRoomService.java b/src/main/java/wooteco/chess/service/SparkRoomService.java deleted file mode 100644 index c2209a111f..0000000000 --- a/src/main/java/wooteco/chess/service/SparkRoomService.java +++ /dev/null @@ -1,31 +0,0 @@ -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 index 4fd36b54df..a66361ed87 100644 --- a/src/main/java/wooteco/chess/service/SpringGameService.java +++ b/src/main/java/wooteco/chess/service/SpringGameService.java @@ -2,16 +2,18 @@ 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.dto.RoomResponseDto; +import wooteco.chess.repository.GameDAO; 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 wooteco.chess.dto.MoveRequestDto; +import wooteco.chess.dto.MoveResponseDto; +import wooteco.chess.dto.PiecesResponseDto; +import wooteco.chess.repository.RoomRepository; +import wooteco.chess.repository.entity.RoomEntity; import java.sql.SQLException; import java.util.List; @@ -23,29 +25,31 @@ public class SpringGameService { private GameDAO gameDAO; @Autowired - private RoomDAO roomDAO; + private RoomRepository roomRepository; - public MoveResponseDTO initialize(int roomId) throws SQLException { - roomDAO.updateRoomColorById(roomId, Color.WHITE); + public MoveResponseDto initialize(int roomId) throws SQLException { + roomRepository.updateRoomColorById(roomId, Color.WHITE.name()); Pieces pieces = new Pieces(Pieces.initPieces()); gameDAO.addAllPiecesById(roomId, pieces); - return new MoveResponseDTO(new PiecesResponseDTO(pieces).getPieces(), Color.WHITE, false); + return new MoveResponseDto(new PiecesResponseDto(pieces).getPieces(), Color.WHITE, false); } - public MoveResponseDTO move(MoveRequestDTO requestDTO) throws SQLException { + 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); + RoomResponseDto responseDto = roomRepository.findById(roomId) + .map(RoomResponseDto::of) + .orElseThrow(RuntimeException::new); + GameManager gameManager = new GameManager(pieces, Color.valueOf(responseDto.getCurrentColor())); gameManager.validateEndGame(); gameManager.moveFromTo(Position.of(sourcePosition), Position.of(targetPosition)); - roomDAO.updateRoomColorById(roomId, gameManager.getCurrentColor()); + roomRepository.updateRoomColorById(roomId, gameManager.getCurrentColor().name()); gameDAO.removeAllPiecesById(roomId); gameDAO.addAllPiecesById(roomId, pieces); - return new MoveResponseDTO(new PiecesResponseDTO(pieces).getPieces(), roomDAO.findRoomColorById(roomId), + return new MoveResponseDto(new PiecesResponseDto(pieces).getPieces(), Color.valueOf(responseDto.getCurrentColor()), gameManager.isKingDead()); } @@ -56,30 +60,42 @@ public double getScore(int roomId, Color color) throws SQLException { return PieceScore.calculateByColor(gameManager, color); } - public PiecesResponseDTO getPiecesResponseDTO(int roomId) throws SQLException { + public PiecesResponseDto getPiecesResponseDTO(int roomId) throws SQLException { Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); - return new PiecesResponseDTO(pieces); + return new PiecesResponseDto(pieces); } private boolean isKingDead(final int roomId) throws SQLException { Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); - Color currentColor = roomDAO.findRoomColorById(roomId); + RoomResponseDto responseDto = roomRepository.findById(roomId) + .map(RoomResponseDto::of) + .orElseThrow(RuntimeException::new); + Color currentColor = Color.valueOf(responseDto.getCurrentColor()); + return pieces.isKingDead(currentColor); } private Color getCurrentColor(final int roomId) throws SQLException { - return roomDAO.findRoomColorById(roomId); + RoomResponseDto responseDto = roomRepository.findById(roomId) + .map(RoomResponseDto::of) + .orElseThrow(RuntimeException::new); + return Color.valueOf(responseDto.getCurrentColor()); } 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)); + RoomResponseDto responseDto = roomRepository.findById(roomId) + .map(RoomResponseDto::of) + .orElseThrow(RuntimeException::new); + Color currentColor = Color.valueOf(responseDto.getCurrentColor()); + + GameManager gameManager = new GameManager(pieces, currentColor); return gameManager.getMovablePositions(Position.of(sourcePosition)); } - public MoveResponseDTO createMoveResponseDTO(final int roomId) throws SQLException { - return new MoveResponseDTO(getPiecesResponseDTO(roomId).getPieces(), + 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/SpringRoomService.java b/src/main/java/wooteco/chess/service/SpringRoomService.java index 3cf2f4963d..70269d45c9 100644 --- a/src/main/java/wooteco/chess/service/SpringRoomService.java +++ b/src/main/java/wooteco/chess/service/SpringRoomService.java @@ -2,28 +2,34 @@ 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 wooteco.chess.dto.RoomResponseDto; +import wooteco.chess.repository.RoomRepository; +import wooteco.chess.repository.entity.RoomEntity; import java.sql.SQLException; +import java.util.ArrayList; import java.util.List; @Service public class SpringRoomService { @Autowired - private RoomDAO roomDAO; + private RoomRepository roomRepository; public void addRoom(String roomName) throws SQLException { - roomDAO.addRoom(roomName, Color.WHITE.name()); + roomRepository.save(new RoomEntity(roomName, Color.WHITE.name())); } public void removeRoom(int roomId) throws SQLException { - roomDAO.removeRoomById(roomId); + roomRepository.deleteById(roomId); } - public List findAllRoom() throws SQLException { - return roomDAO.findAllRoom(); + public List findAllRoom() throws SQLException { + List rooms = new ArrayList<>(); + for (final RoomEntity roomEntity : roomRepository.findAll()) { + rooms.add(RoomResponseDto.of(roomEntity)); + } + return rooms; } } diff --git a/src/main/java/wooteco/chess/sparkcontroller/SparkGameController.java b/src/main/java/wooteco/chess/sparkcontroller/SparkGameController.java deleted file mode 100644 index 87d98a5ef2..0000000000 --- a/src/main/java/wooteco/chess/sparkcontroller/SparkGameController.java +++ /dev/null @@ -1,97 +0,0 @@ -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 deleted file mode 100644 index cc21a2e285..0000000000 --- a/src/main/java/wooteco/chess/sparkcontroller/SparkRoomController.java +++ /dev/null @@ -1,55 +0,0 @@ -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/templates/game.hbs b/src/main/resources/templates/game.hbs index 3383d6b83e..e904598bd4 100644 --- a/src/main/resources/templates/game.hbs +++ b/src/main/resources/templates/game.hbs @@ -24,7 +24,7 @@
- +

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

현재 턴은 입니다.
diff --git a/src/main/resources/templates/index.html b/src/main/resources/templates/index.html index fd2cbbbc91..3f755100e1 100644 --- a/src/main/resources/templates/index.html +++ b/src/main/resources/templates/index.html @@ -20,7 +20,7 @@

전체 방 목록

- {{#if rooms}} + {{#if roomResponseDtos}} @@ -30,7 +30,7 @@

전체 방 목록

- {{#each rooms}} + {{#each roomResponseDtos}} @@ -45,7 +45,7 @@

전체 방 목록

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

{{/if}} - +
방을 만드려면 방 제목을 입력해주세요. @@ -53,7 +53,7 @@

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

-
+
방에 입장하려면 방 번호를 입력해주세요. @@ -76,7 +76,7 @@

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

function deleteRoom(roomId) { console.log("deleteRoom : " + roomId); let oReq = new XMLHttpRequest(); - oReq.open('GET', '/rooms/remove?roomId=' + roomId); + oReq.open('GET', '/roomResponseDtos/remove?roomId=' + roomId); oReq.send(); } From 12ae667f6017512938e9c4e9824c68d6ee60d11a Mon Sep 17 00:00:00 2001 From: dd Date: Tue, 28 Apr 2020 22:34:40 +0900 Subject: [PATCH 04/10] =?UTF-8?q?refactor=20:=20Spring=20data=20jdbc=20?= =?UTF-8?q?=EC=97=90=20=EB=A7=9E=EB=8F=84=EB=A1=9D=20=ED=85=8C=EC=9D=B4?= =?UTF-8?q?=EB=B8=94,=20=EC=97=94=ED=8B=B0=ED=8B=B0,=20dto=20=EC=84=A4?= =?UTF-8?q?=EA=B3=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 1 + .../wooteco/chess/config/ModelConfig.java | 14 + .../controller/SpringGameController.java | 31 +- .../controller/SpringRoomController.java | 13 +- .../wooteco/chess/dto/GameManagerDto.java | 38 -- .../wooteco/chess/dto/GameRequestDto.java | 16 + ...eResponseDto.java => GameResponseDto.java} | 4 +- .../wooteco/chess/dto/MovablePositionDto.java | 15 - .../wooteco/chess/dto/MovePositionDto.java | 19 - .../wooteco/chess/dto/MoveRequestDto.java | 12 +- src/main/java/wooteco/chess/dto/RoomDto.java | 33 ++ src/main/java/wooteco/chess/dto/RoomName.java | 21 -- .../wooteco/chess/dto/RoomResponseDto.java | 31 -- .../wooteco/chess/repository/GameDAO.java | 116 ------ .../chess/repository/GameRepository.java | 9 + .../chess/repository/JdbcTemplate.java | 40 --- .../chess/repository/PieceRepository.java | 10 + .../repository/PreparedStatementSetter.java | 8 - .../chess/repository/RoomRepository.java | 9 +- .../wooteco/chess/repository/RowMapper.java | 8 - .../chess/repository/entity/GameEntity.java | 35 ++ .../chess/repository/entity/PieceEntity.java | 31 ++ .../chess/repository/entity/RoomEntity.java | 46 +-- .../chess/service/SpringGameService.java | 147 +++++--- .../chess/service/SpringRoomService.java | 49 ++- .../wooteco/chess/util/HandlebarsUtil.java | 12 - .../wooteco/chess/util/JDBCConnector.java | 33 -- src/main/resources/application.properties | 1 - src/main/resources/schema.sql | 17 + src/main/resources/templates/game.html | 339 ------------------ src/main/resources/templates/index.hbs | 4 +- src/main/resources/templates/index.html | 84 ----- 32 files changed, 355 insertions(+), 891 deletions(-) create mode 100644 src/main/java/wooteco/chess/config/ModelConfig.java delete mode 100644 src/main/java/wooteco/chess/dto/GameManagerDto.java create mode 100644 src/main/java/wooteco/chess/dto/GameRequestDto.java rename src/main/java/wooteco/chess/dto/{MoveResponseDto.java => GameResponseDto.java} (89%) delete mode 100644 src/main/java/wooteco/chess/dto/MovablePositionDto.java delete mode 100644 src/main/java/wooteco/chess/dto/MovePositionDto.java create mode 100644 src/main/java/wooteco/chess/dto/RoomDto.java delete mode 100644 src/main/java/wooteco/chess/dto/RoomName.java delete mode 100644 src/main/java/wooteco/chess/dto/RoomResponseDto.java delete mode 100644 src/main/java/wooteco/chess/repository/GameDAO.java create mode 100644 src/main/java/wooteco/chess/repository/GameRepository.java delete mode 100644 src/main/java/wooteco/chess/repository/JdbcTemplate.java create mode 100644 src/main/java/wooteco/chess/repository/PieceRepository.java delete mode 100644 src/main/java/wooteco/chess/repository/PreparedStatementSetter.java delete mode 100644 src/main/java/wooteco/chess/repository/RowMapper.java create mode 100644 src/main/java/wooteco/chess/repository/entity/GameEntity.java create mode 100644 src/main/java/wooteco/chess/repository/entity/PieceEntity.java delete mode 100644 src/main/java/wooteco/chess/util/HandlebarsUtil.java delete mode 100644 src/main/java/wooteco/chess/util/JDBCConnector.java create mode 100644 src/main/resources/schema.sql delete mode 100644 src/main/resources/templates/game.html delete mode 100644 src/main/resources/templates/index.html diff --git a/build.gradle b/build.gradle index ddf894cb22..5e26eea49d 100644 --- a/build.gradle +++ b/build.gradle @@ -14,6 +14,7 @@ repositories { dependencies { compile('mysql:mysql-connector-java:8.0.16') + compile group: 'org.modelmapper', name: 'modelmapper', version: '2.3.7' implementation 'com.sparkjava:spark-core:2.9.0' implementation 'com.sparkjava:spark-template-handlebars:2.7.1' implementation 'org.springframework.boot:spring-boot-starter-web' diff --git a/src/main/java/wooteco/chess/config/ModelConfig.java b/src/main/java/wooteco/chess/config/ModelConfig.java new file mode 100644 index 0000000000..faa109140f --- /dev/null +++ b/src/main/java/wooteco/chess/config/ModelConfig.java @@ -0,0 +1,14 @@ +package wooteco.chess.config; + +import org.modelmapper.ModelMapper; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ModelConfig { + + @Bean + public ModelMapper modelMapper(){ + return new ModelMapper(); + } +} diff --git a/src/main/java/wooteco/chess/controller/SpringGameController.java b/src/main/java/wooteco/chess/controller/SpringGameController.java index 9e4c4a5c98..94afd20e7e 100644 --- a/src/main/java/wooteco/chess/controller/SpringGameController.java +++ b/src/main/java/wooteco/chess/controller/SpringGameController.java @@ -4,7 +4,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import wooteco.chess.domain.Color; -import wooteco.chess.dto.MoveResponseDto; +import wooteco.chess.dto.GameRequestDto; +import wooteco.chess.dto.GameResponseDto; import wooteco.chess.dto.GameStatusDto; import wooteco.chess.dto.MoveRequestDto; import wooteco.chess.service.SpringGameService; @@ -12,6 +13,7 @@ import javax.servlet.http.HttpServletRequest; import java.sql.SQLException; import java.util.List; +import java.util.UUID; @RestController @RequestMapping("/game") @@ -24,36 +26,33 @@ public SpringGameController(final SpringGameService gameService) { } @GetMapping("/init") - public MoveResponseDto init(@RequestParam Integer roomId) throws SQLException { - return gameService.initialize(roomId); + public GameResponseDto init(@RequestParam GameRequestDto gameRequestDto) throws SQLException { + return gameService.initialize(gameRequestDto); } @PostMapping("/move") - public ResponseEntity move(@RequestBody MoveRequestDto requestDTO) throws SQLException { + public ResponseEntity move(@RequestBody MoveRequestDto requestDTO) throws SQLException { try { return ResponseEntity.status(HttpStatus.OK).body(gameService.move(requestDTO)); } catch (IllegalArgumentException e) { - MoveResponseDto moveResponseDTO = gameService.createMoveResponseDTO(requestDTO.getRoomId()); - moveResponseDTO.setErrorMessage(e.getMessage()); - return ResponseEntity.status(HttpStatus.OK).body(moveResponseDTO); + GameResponseDto gameResponseDTO = gameService.findAllPieces(requestDTO.getId()); + gameResponseDTO.setErrorMessage(e.getMessage()); + return ResponseEntity.status(HttpStatus.OK).body(gameResponseDTO); } } @GetMapping("/status") - public GameStatusDto showStatus(@RequestParam Integer roomId) throws SQLException { - return new GameStatusDto(gameService.getScore(roomId, Color.WHITE), gameService.getScore(roomId, Color.BLACK)); + public GameStatusDto showStatus(@RequestParam GameRequestDto gameRequestDto) throws SQLException { + return new GameStatusDto(gameService.getScore(gameRequestDto), gameService.getScore(gameRequestDto)); } @GetMapping("/load") - public MoveResponseDto load(@RequestParam Integer roomId) throws SQLException { - return gameService.createMoveResponseDTO(roomId); + public GameResponseDto load(@RequestParam UUID roomId) throws SQLException { + return gameService.findAllPieces(roomId); } @GetMapping("/get") - public List getMovablePositions(final HttpServletRequest request) throws SQLException { - int roomId = Integer.parseInt(request.getParameter("roomId")); - String sourcePosition = request.getParameter("sourcePosition"); - - return gameService.getMovablePositions(roomId, sourcePosition); + public List getMovablePositions(final MoveRequestDto moveRequestDto) throws SQLException { + return gameService.getMovablePositions(moveRequestDto); } } diff --git a/src/main/java/wooteco/chess/controller/SpringRoomController.java b/src/main/java/wooteco/chess/controller/SpringRoomController.java index dcdf70153e..95063ec633 100644 --- a/src/main/java/wooteco/chess/controller/SpringRoomController.java +++ b/src/main/java/wooteco/chess/controller/SpringRoomController.java @@ -6,8 +6,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; -import wooteco.chess.dto.RoomResponseDto; -import wooteco.chess.dto.RoomName; +import wooteco.chess.dto.RoomDto; import wooteco.chess.service.SpringRoomService; import javax.validation.Valid; @@ -26,7 +25,7 @@ private SpringRoomController(final SpringRoomService roomService) { @GetMapping public String getAllRooms(Model model) throws SQLException { - List rooms = roomService.findAllRoom(); + List rooms = roomService.findAllRoom(); model.addAttribute("rooms", rooms); return "index"; @@ -40,18 +39,18 @@ public String enterRoom(@RequestParam(value = "roomId") Integer roomId, Model mo // TODO: 2020/04/22 valid 에러페이지 이동 문제 @GetMapping("/create") - public String createRoom(@Valid RoomName roomName, Errors errors, Model model) throws SQLException { + public String createRoom(@Valid RoomDto roomId, Errors errors, Model model) throws SQLException { if (errors.hasErrors()) { model.addAttribute("errors", errors); return getAllRooms(model); } - roomService.addRoom(roomName.getRoomName()); + roomService.addRoom(roomId); return "redirect:/rooms"; } @GetMapping("/remove") - public String removeRoom(@RequestParam(value = "roomId") Integer roomId) throws SQLException { - roomService.removeRoom(roomId); + public String removeRoom(@RequestParam(value = "roomId") RoomDto roomDto) throws SQLException { + roomService.removeRoom(roomDto); return "redirect:/rooms"; } } diff --git a/src/main/java/wooteco/chess/dto/GameManagerDto.java b/src/main/java/wooteco/chess/dto/GameManagerDto.java deleted file mode 100644 index 0b879334f6..0000000000 --- a/src/main/java/wooteco/chess/dto/GameManagerDto.java +++ /dev/null @@ -1,38 +0,0 @@ -package wooteco.chess.dto; - -import wooteco.chess.domain.Color; - -import java.util.List; - -public class GameManagerDto { - private final List pieces; - private final Color currentColor; - private final boolean kingDead; - private String errorMessage; - - public GameManagerDto(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/dto/GameRequestDto.java b/src/main/java/wooteco/chess/dto/GameRequestDto.java new file mode 100644 index 0000000000..a63f75be15 --- /dev/null +++ b/src/main/java/wooteco/chess/dto/GameRequestDto.java @@ -0,0 +1,16 @@ +package wooteco.chess.dto; + +import java.util.UUID; + +public class GameRequestDto { + + private UUID id; + + public GameRequestDto(final UUID id) { + this.id = id; + } + + public UUID getId() { + return id; + } +} diff --git a/src/main/java/wooteco/chess/dto/MoveResponseDto.java b/src/main/java/wooteco/chess/dto/GameResponseDto.java similarity index 89% rename from src/main/java/wooteco/chess/dto/MoveResponseDto.java rename to src/main/java/wooteco/chess/dto/GameResponseDto.java index 06e57cd7c3..888940bc71 100644 --- a/src/main/java/wooteco/chess/dto/MoveResponseDto.java +++ b/src/main/java/wooteco/chess/dto/GameResponseDto.java @@ -4,13 +4,13 @@ import java.util.List; -public class MoveResponseDto { +public class GameResponseDto { 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) { + public GameResponseDto(final List pieces, final Color currentColor, final boolean kingDead) { this.pieces = pieces; this.currentColor = currentColor; this.kingDead = kingDead; diff --git a/src/main/java/wooteco/chess/dto/MovablePositionDto.java b/src/main/java/wooteco/chess/dto/MovablePositionDto.java deleted file mode 100644 index 5e51d2e894..0000000000 --- a/src/main/java/wooteco/chess/dto/MovablePositionDto.java +++ /dev/null @@ -1,15 +0,0 @@ -package wooteco.chess.dto; - -import java.util.List; - -public class MovablePositionDto { - private final List positions; - - public MovablePositionDto(final List positions) { - this.positions = positions; - } - - public List getPositions() { - return positions; - } -} diff --git a/src/main/java/wooteco/chess/dto/MovePositionDto.java b/src/main/java/wooteco/chess/dto/MovePositionDto.java deleted file mode 100644 index 10c8bafb21..0000000000 --- a/src/main/java/wooteco/chess/dto/MovePositionDto.java +++ /dev/null @@ -1,19 +0,0 @@ -package wooteco.chess.dto; - -public class MovePositionDto { - private final String sourcePosition; - private final String targetPosition; - - public MovePositionDto(final String sourcePosition, final String targetPosition) { - this.sourcePosition = sourcePosition; - this.targetPosition = targetPosition; - } - - public String getSourcePosition() { - return sourcePosition; - } - - public String getTargetPosition() { - return targetPosition; - } -} diff --git a/src/main/java/wooteco/chess/dto/MoveRequestDto.java b/src/main/java/wooteco/chess/dto/MoveRequestDto.java index ed738e24f2..a6b64428ad 100644 --- a/src/main/java/wooteco/chess/dto/MoveRequestDto.java +++ b/src/main/java/wooteco/chess/dto/MoveRequestDto.java @@ -1,19 +1,21 @@ package wooteco.chess.dto; +import java.util.UUID; + public class MoveRequestDto { - private Integer roomId; + private UUID id; private String sourcePosition; private String targetPosition; - public MoveRequestDto(final Integer roomId, final String sourcePosition, final String targetPosition) { - this.roomId = roomId; + public MoveRequestDto(final UUID id, final String sourcePosition, final String targetPosition) { + this.id = id; this.sourcePosition = sourcePosition; this.targetPosition = targetPosition; } - public Integer getRoomId() { - return roomId; + public UUID getId() { + return id; } public String getSourcePosition() { diff --git a/src/main/java/wooteco/chess/dto/RoomDto.java b/src/main/java/wooteco/chess/dto/RoomDto.java new file mode 100644 index 0000000000..4c1e161296 --- /dev/null +++ b/src/main/java/wooteco/chess/dto/RoomDto.java @@ -0,0 +1,33 @@ +package wooteco.chess.dto; + +import javax.validation.constraints.NotEmpty; +import java.util.UUID; + +public class RoomDto { + + private UUID id; + + @NotEmpty + private String roomName; + + @NotEmpty + private String password; + + public RoomDto(@NotEmpty final UUID id, @NotEmpty final String roomName, @NotEmpty final String password) { + this.id = id; + this.roomName = roomName; + this.password = password; + } + + public UUID getId() { + return id; + } + + public String getRoomName() { + return roomName; + } + + public String getPassword() { + return password; + } +} diff --git a/src/main/java/wooteco/chess/dto/RoomName.java b/src/main/java/wooteco/chess/dto/RoomName.java deleted file mode 100644 index 8876eb61ef..0000000000 --- a/src/main/java/wooteco/chess/dto/RoomName.java +++ /dev/null @@ -1,21 +0,0 @@ -package wooteco.chess.dto; - -import javax.validation.constraints.NotEmpty; - -public class RoomName { - - @NotEmpty - private String roomName; - - public RoomName(final String roomName) { - this.roomName = roomName; - } - - public String getRoomName() { - return roomName; - } - - public void setRoomName(final String roomName) { - this.roomName = roomName; - } -} diff --git a/src/main/java/wooteco/chess/dto/RoomResponseDto.java b/src/main/java/wooteco/chess/dto/RoomResponseDto.java deleted file mode 100644 index 95a4fcec09..0000000000 --- a/src/main/java/wooteco/chess/dto/RoomResponseDto.java +++ /dev/null @@ -1,31 +0,0 @@ -package wooteco.chess.dto; - -import wooteco.chess.repository.entity.RoomEntity; - -public class RoomResponseDto { - private final int roomId; - private final String roomName; - private final String currentColor; - - private RoomResponseDto(int roomId, String roomName, String currentColor) { - this.roomId = roomId; - this.roomName = roomName; - this.currentColor = currentColor; - } - - public static RoomResponseDto of(RoomEntity roomEntity) { - return new RoomResponseDto(roomEntity.getRoomId(), roomEntity.getRoomName(), roomEntity.getCurrentColor()); - } - - public int getRoomId() { - return roomId; - } - - public String getRoomName() { - return roomName; - } - - public String getCurrentColor() { - return currentColor; - } -} diff --git a/src/main/java/wooteco/chess/repository/GameDAO.java b/src/main/java/wooteco/chess/repository/GameDAO.java deleted file mode 100644 index aab2396eb5..0000000000 --- a/src/main/java/wooteco/chess/repository/GameDAO.java +++ /dev/null @@ -1,116 +0,0 @@ -package wooteco.chess.repository; - -import org.springframework.stereotype.Repository; -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.SQLException; -import java.util.HashMap; -import java.util.Map; - -@Repository -public class GameDAO { - public void removeAllPiecesById(int roomId) throws SQLException { - String query = "DELETE FROM board WHERE room_id = ?"; - - PreparedStatementSetter pss = pstmt -> 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 = pstmt -> { - 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 = pstmt -> { - 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 = pstmt -> 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 = pstmt -> { - 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 = pstmt -> pstmt.setString(1, position); - - RowMapper rm = rs -> { - 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 = pstmt -> pstmt.setInt(1, roomId); - - RowMapper rm = rs -> { - 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/repository/GameRepository.java b/src/main/java/wooteco/chess/repository/GameRepository.java new file mode 100644 index 0000000000..75fea038cd --- /dev/null +++ b/src/main/java/wooteco/chess/repository/GameRepository.java @@ -0,0 +1,9 @@ +package wooteco.chess.repository; + +import org.springframework.data.repository.CrudRepository; +import wooteco.chess.repository.entity.GameEntity; + +import java.util.UUID; + +public interface GameRepository extends CrudRepository { +} diff --git a/src/main/java/wooteco/chess/repository/JdbcTemplate.java b/src/main/java/wooteco/chess/repository/JdbcTemplate.java deleted file mode 100644 index fef402bfd5..0000000000 --- a/src/main/java/wooteco/chess/repository/JdbcTemplate.java +++ /dev/null @@ -1,40 +0,0 @@ -package wooteco.chess.repository; - -import wooteco.chess.util.JDBCConnector; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class JdbcTemplate { - - public void executeUpdate(String query, PreparedStatementSetter pss) throws SQLException { - try (Connection con = JDBCConnector.getConnection(); - PreparedStatement pstmt = con.prepareStatement(query) - ) { - pss.setParameters(pstmt); - pstmt.executeUpdate(); - } - } - - public void executeBatch(String query, PreparedStatementSetter pss) throws SQLException { - try (Connection con = JDBCConnector.getConnection(); - PreparedStatement pstmt = con.prepareStatement(query) - ) { - pss.setParameters(pstmt); - pstmt.executeBatch(); - } - } - - public T executeQuery(String query, PreparedStatementSetter pss, RowMapper rm) throws SQLException { - try (Connection con = JDBCConnector.getConnection(); - PreparedStatement pstmt = con.prepareStatement(query) - ) { - pss.setParameters(pstmt); - try (ResultSet rs = pstmt.executeQuery()) { - return rm.mapRow(rs); - } - } - } -} diff --git a/src/main/java/wooteco/chess/repository/PieceRepository.java b/src/main/java/wooteco/chess/repository/PieceRepository.java new file mode 100644 index 0000000000..b031e2528c --- /dev/null +++ b/src/main/java/wooteco/chess/repository/PieceRepository.java @@ -0,0 +1,10 @@ +package wooteco.chess.repository; + +import org.springframework.data.repository.CrudRepository; +import wooteco.chess.repository.entity.PieceEntity; + +import java.util.UUID; + +public interface PieceRepository extends CrudRepository { + +} diff --git a/src/main/java/wooteco/chess/repository/PreparedStatementSetter.java b/src/main/java/wooteco/chess/repository/PreparedStatementSetter.java deleted file mode 100644 index af2b11d862..0000000000 --- a/src/main/java/wooteco/chess/repository/PreparedStatementSetter.java +++ /dev/null @@ -1,8 +0,0 @@ -package wooteco.chess.repository; - -import java.sql.PreparedStatement; -import java.sql.SQLException; - -public interface PreparedStatementSetter { - void setParameters(final PreparedStatement pstmt) throws SQLException; -} diff --git a/src/main/java/wooteco/chess/repository/RoomRepository.java b/src/main/java/wooteco/chess/repository/RoomRepository.java index 19b23ede73..2dabeefbc2 100644 --- a/src/main/java/wooteco/chess/repository/RoomRepository.java +++ b/src/main/java/wooteco/chess/repository/RoomRepository.java @@ -7,10 +7,11 @@ import wooteco.chess.domain.Color; import wooteco.chess.repository.entity.RoomEntity; -public interface RoomRepository extends CrudRepository { +import java.util.List; +import java.util.UUID; - @Modifying - @Query("UPDATE room SET room_color = :currentColor WHERE room_id = :roomId") - void updateRoomColorById(int roomId, String currentColor); +public interface RoomRepository extends CrudRepository { + @Override + List findAll(); } diff --git a/src/main/java/wooteco/chess/repository/RowMapper.java b/src/main/java/wooteco/chess/repository/RowMapper.java deleted file mode 100644 index 6cbb3d7f5c..0000000000 --- a/src/main/java/wooteco/chess/repository/RowMapper.java +++ /dev/null @@ -1,8 +0,0 @@ -package wooteco.chess.repository; - -import java.sql.ResultSet; -import java.sql.SQLException; - -public interface RowMapper { - T mapRow(final ResultSet rs) throws SQLException; -} diff --git a/src/main/java/wooteco/chess/repository/entity/GameEntity.java b/src/main/java/wooteco/chess/repository/entity/GameEntity.java new file mode 100644 index 0000000000..aa14f7557f --- /dev/null +++ b/src/main/java/wooteco/chess/repository/entity/GameEntity.java @@ -0,0 +1,35 @@ +package wooteco.chess.repository.entity; + +import org.springframework.data.annotation.Id; +import org.springframework.data.relational.core.mapping.Table; +import wooteco.chess.domain.Color; + +import java.util.Set; +import java.util.UUID; + +@Table("game") +public class GameEntity { + private Color turn; + private Set piece; + + public GameEntity(final Color turn, final Set piece) { + this.turn = turn; + this.piece = piece; + } + + public Color getTurn() { + return turn; + } + + public Set getPiece() { + return piece; + } + + public void updatePiece(final Set piece) { + this.piece = piece; + } + + public void updateTurn(final Color turn) { + this.turn = turn; + } +} diff --git a/src/main/java/wooteco/chess/repository/entity/PieceEntity.java b/src/main/java/wooteco/chess/repository/entity/PieceEntity.java new file mode 100644 index 0000000000..09046833f6 --- /dev/null +++ b/src/main/java/wooteco/chess/repository/entity/PieceEntity.java @@ -0,0 +1,31 @@ +package wooteco.chess.repository.entity; + +import org.springframework.data.annotation.Id; +import org.springframework.data.relational.core.mapping.Table; + +import java.util.UUID; + +@Table("piece") +public class PieceEntity { + private String name; + private String color; + private String position; + + public PieceEntity(final String name, final String color, final String position) { + this.name = name; + this.color = color; + this.position = position; + } + + public String getName() { + return name; + } + + public String getColor() { + return color; + } + + public String getPosition() { + return position; + } +} diff --git a/src/main/java/wooteco/chess/repository/entity/RoomEntity.java b/src/main/java/wooteco/chess/repository/entity/RoomEntity.java index 1f847fd7ab..25e6196803 100644 --- a/src/main/java/wooteco/chess/repository/entity/RoomEntity.java +++ b/src/main/java/wooteco/chess/repository/entity/RoomEntity.java @@ -6,41 +6,43 @@ import org.springframework.data.relational.core.mapping.Table; import wooteco.chess.domain.Color; +import javax.annotation.Generated; +import java.util.Set; +import java.util.UUID; + @Table("room") public class RoomEntity { @Id - private Integer roomId; - - private String roomName; - - @Column("room_color") - private String currentColor; - - - private RoomEntity(){ + private UUID id; + private String name; + private String password; + @Column(value = "room") + private GameEntity game; + + public RoomEntity(final String name, final String password, final GameEntity game) { + this.name = name; + this.password = password; + this.game = game; } - public RoomEntity(final String roomName, final String currentColor) { - this.roomName = roomName; - this.currentColor = currentColor; + public UUID getId() { + return id; } - public RoomEntity(final int roomId, final String roomName, final String currentColor) { - this.roomId = roomId; - this.roomName = roomName; - this.currentColor = currentColor; + public String getName() { + return name; } - public int getRoomId() { - return roomId; + public String getPassword() { + return password; } - public String getRoomName() { - return roomName; + public GameEntity getGame() { + return game; } - public String getCurrentColor() { - return currentColor; + public void updateGame(final GameEntity game) { + this.game = game; } } diff --git a/src/main/java/wooteco/chess/service/SpringGameService.java b/src/main/java/wooteco/chess/service/SpringGameService.java index a66361ed87..cb98275790 100644 --- a/src/main/java/wooteco/chess/service/SpringGameService.java +++ b/src/main/java/wooteco/chess/service/SpringGameService.java @@ -2,100 +2,135 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import wooteco.chess.dto.RoomResponseDto; -import wooteco.chess.repository.GameDAO; +import org.springframework.transaction.annotation.Transactional; +import wooteco.chess.domain.piece.Piece; +import wooteco.chess.domain.piece.PieceMapper; +import wooteco.chess.dto.*; +import wooteco.chess.repository.GameRepository; +import wooteco.chess.repository.PieceRepository; 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 wooteco.chess.repository.RoomRepository; +import wooteco.chess.repository.entity.GameEntity; +import wooteco.chess.repository.entity.PieceEntity; import wooteco.chess.repository.entity.RoomEntity; import java.sql.SQLException; import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; @Service public class SpringGameService { - @Autowired - private GameDAO gameDAO; - @Autowired private RoomRepository roomRepository; - public MoveResponseDto initialize(int roomId) throws SQLException { - roomRepository.updateRoomColorById(roomId, Color.WHITE.name()); - Pieces pieces = new Pieces(Pieces.initPieces()); - gameDAO.addAllPiecesById(roomId, pieces); - return new MoveResponseDto(new PiecesResponseDto(pieces).getPieces(), Color.WHITE, false); + @Transactional + public GameResponseDto initialize(GameRequestDto request) throws SQLException { + RoomEntity roomEntity = roomRepository.findById(request.getId()) + .orElseThrow(RuntimeException::new); + Set pieceEntities = convertPiecesToPieceEntity(Pieces.initPieces()); + GameEntity gameEntity = new GameEntity(Color.WHITE, pieceEntities); + roomEntity.updateGame(gameEntity); + RoomEntity persistEntity = roomRepository.save(roomEntity); + + return convertRoomEntityToGameDto(persistEntity); } - public MoveResponseDto move(MoveRequestDto requestDTO) throws SQLException { - Integer roomId = requestDTO.getRoomId(); - String sourcePosition = requestDTO.getSourcePosition(); - String targetPosition = requestDTO.getTargetPosition(); + public GameResponseDto move(MoveRequestDto moveRequestDto) throws SQLException { + UUID id = moveRequestDto.getId(); + String sourcePosition = moveRequestDto.getSourcePosition(); + String targetPosition = moveRequestDto.getTargetPosition(); - Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); - RoomResponseDto responseDto = roomRepository.findById(roomId) - .map(RoomResponseDto::of) + RoomEntity roomEntity = roomRepository.findById(id) .orElseThrow(RuntimeException::new); - GameManager gameManager = new GameManager(pieces, Color.valueOf(responseDto.getCurrentColor())); + GameEntity gameEntity = roomEntity.getGame(); + + Pieces pieces = new Pieces(convertPieceEntityToPieces(gameEntity.getPiece())); + + GameManager gameManager = new GameManager(pieces, gameEntity.getTurn()); gameManager.validateEndGame(); gameManager.moveFromTo(Position.of(sourcePosition), Position.of(targetPosition)); - roomRepository.updateRoomColorById(roomId, gameManager.getCurrentColor().name()); - gameDAO.removeAllPiecesById(roomId); - gameDAO.addAllPiecesById(roomId, pieces); - return new MoveResponseDto(new PiecesResponseDto(pieces).getPieces(), Color.valueOf(responseDto.getCurrentColor()), - gameManager.isKingDead()); - } - public double getScore(int roomId, Color color) throws SQLException { - Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); - GameManager gameManager = new GameManager(pieces, color); + Pieces movedPieces = gameManager.getPieces(); + gameEntity.updatePiece(convertPiecesToPieceEntity(movedPieces.getPieces())); + gameEntity.updateTurn(gameManager.getCurrentColor()); - return PieceScore.calculateByColor(gameManager, color); - } + roomEntity.updateGame(gameEntity); + roomRepository.save(roomEntity); - public PiecesResponseDto getPiecesResponseDTO(int roomId) throws SQLException { - Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); - return new PiecesResponseDto(pieces); + return convertRoomEntityToGameDto(roomEntity); } - private boolean isKingDead(final int roomId) throws SQLException { - Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); - RoomResponseDto responseDto = roomRepository.findById(roomId) - .map(RoomResponseDto::of) + public double getScore(final GameRequestDto gameRequestDto) throws SQLException { + UUID id = gameRequestDto.getId(); + + RoomEntity roomEntity = roomRepository.findById(id) .orElseThrow(RuntimeException::new); - Color currentColor = Color.valueOf(responseDto.getCurrentColor()); - return pieces.isKingDead(currentColor); - } + GameEntity gameEntity = roomEntity.getGame(); - private Color getCurrentColor(final int roomId) throws SQLException { - RoomResponseDto responseDto = roomRepository.findById(roomId) - .map(RoomResponseDto::of) - .orElseThrow(RuntimeException::new); - return Color.valueOf(responseDto.getCurrentColor()); + + Map originPieces = convertPieceEntityToPieces(gameEntity.getPiece()); + Pieces pieces = new Pieces(originPieces); + GameManager gameManager = new GameManager(pieces, gameEntity.getTurn()); + + return PieceScore.calculateByColor(gameManager, gameEntity.getTurn()); } - public List getMovablePositions(final int roomId, final String sourcePosition) throws SQLException { - Pieces pieces = new Pieces(gameDAO.findAllPiecesById(roomId)); - RoomResponseDto responseDto = roomRepository.findById(roomId) - .map(RoomResponseDto::of) + public List getMovablePositions(final MoveRequestDto moveRequestDto) throws SQLException { + UUID id = moveRequestDto.getId(); + String sourcePosition = moveRequestDto.getSourcePosition(); + + RoomEntity roomEntity = roomRepository.findById(id) .orElseThrow(RuntimeException::new); - Color currentColor = Color.valueOf(responseDto.getCurrentColor()); + GameEntity game = roomEntity.getGame(); + Map originPieces = convertPieceEntityToPieces(game.getPiece()); + Pieces pieces = new Pieces(originPieces); - GameManager gameManager = new GameManager(pieces, currentColor); + GameManager gameManager = new GameManager(pieces, game.getTurn()); return gameManager.getMovablePositions(Position.of(sourcePosition)); } - public MoveResponseDto createMoveResponseDTO(final int roomId) throws SQLException { - return new MoveResponseDto(getPiecesResponseDTO(roomId).getPieces(), - getCurrentColor(roomId), isKingDead(roomId)); + private GameResponseDto convertRoomEntityToGameDto(final RoomEntity roomEntity) { + GameEntity game = roomEntity.getGame(); + Color turn = game.getTurn(); + Set pieceEntities = game.getPiece(); + Map originPieces = convertPieceEntityToPieces(pieceEntities); + Pieces pieces = new Pieces(originPieces); + boolean kingDead = pieces.isKingDead(turn); + + return new GameResponseDto(new PiecesResponseDto(pieces).getPieces(), turn, kingDead); + } + + private Set convertPiecesToPieceEntity(final Map pieces) { + return pieces.entrySet().stream() + .map(entry -> + new PieceEntity(entry.getValue().getSymbol(), + entry.getValue().getColor().name(), + entry.getKey().getPosition())) + .collect(Collectors.toSet()); + } + + private Map convertPieceEntityToPieces(final Set entity) { + return entity.stream() + .collect(Collectors.toMap( + pieceEntity -> Position.of(pieceEntity.getPosition()), + pieceEntity -> PieceMapper.getInstance().findDBPiece(pieceEntity.getName()) + )); + } + + public GameResponseDto findAllPieces(final UUID roomId) { + return convertRoomEntityToGameDto(roomRepository + .findById(roomId) + .orElseThrow(RuntimeException::new) + ); } } diff --git a/src/main/java/wooteco/chess/service/SpringRoomService.java b/src/main/java/wooteco/chess/service/SpringRoomService.java index 70269d45c9..a14c460b28 100644 --- a/src/main/java/wooteco/chess/service/SpringRoomService.java +++ b/src/main/java/wooteco/chess/service/SpringRoomService.java @@ -1,15 +1,23 @@ package wooteco.chess.service; +import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import wooteco.chess.domain.Color; -import wooteco.chess.dto.RoomResponseDto; +import wooteco.chess.domain.board.Position; +import wooteco.chess.domain.piece.Piece; +import wooteco.chess.domain.piece.Pieces; +import wooteco.chess.dto.RoomDto; import wooteco.chess.repository.RoomRepository; +import wooteco.chess.repository.entity.GameEntity; +import wooteco.chess.repository.entity.PieceEntity; import wooteco.chess.repository.entity.RoomEntity; import java.sql.SQLException; -import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; @Service public class SpringRoomService { @@ -17,19 +25,36 @@ public class SpringRoomService { @Autowired private RoomRepository roomRepository; - public void addRoom(String roomName) throws SQLException { - roomRepository.save(new RoomEntity(roomName, Color.WHITE.name())); + @Autowired + private ModelMapper modelMapper; + + public void addRoom(RoomDto roomDto) throws SQLException { + Set pieceEntities = convertPiecesToPieceEntity(Pieces.initPieces()); + GameEntity gameEntity = new GameEntity(Color.WHITE, pieceEntities); + roomRepository.save(new RoomEntity(roomDto.getRoomName(), roomDto.getPassword(), gameEntity)); + } + + public void removeRoom(RoomDto roomDto) throws SQLException { + roomRepository.deleteById(roomDto.getId()); + } + + public List findAllRoom() throws SQLException { + return convertRoomEntityToDto(roomRepository.findAll()); + } - public void removeRoom(int roomId) throws SQLException { - roomRepository.deleteById(roomId); + private List convertRoomEntityToDto(final List roomEntities) { + return roomEntities.stream() + .map(roomEntity -> new RoomDto(roomEntity.getId(), roomEntity.getName(), roomEntity.getPassword())) + .collect(Collectors.toList()); } - public List findAllRoom() throws SQLException { - List rooms = new ArrayList<>(); - for (final RoomEntity roomEntity : roomRepository.findAll()) { - rooms.add(RoomResponseDto.of(roomEntity)); - } - return rooms; + private Set convertPiecesToPieceEntity(final Map pieces) { + return pieces.entrySet().stream() + .map(entry -> + new PieceEntity(entry.getValue().getSymbol(), + entry.getValue().getColor().name(), + entry.getKey().getPosition())) + .collect(Collectors.toSet()); } } diff --git a/src/main/java/wooteco/chess/util/HandlebarsUtil.java b/src/main/java/wooteco/chess/util/HandlebarsUtil.java deleted file mode 100644 index 4e007fae20..0000000000 --- a/src/main/java/wooteco/chess/util/HandlebarsUtil.java +++ /dev/null @@ -1,12 +0,0 @@ -package wooteco.chess.util; - -import spark.ModelAndView; -import spark.template.handlebars.HandlebarsTemplateEngine; - -import java.util.Map; - -public class HandlebarsUtil { - public static String render(Map model, String templatePath) { - return new HandlebarsTemplateEngine().render(new ModelAndView(model, templatePath)); - } -} diff --git a/src/main/java/wooteco/chess/util/JDBCConnector.java b/src/main/java/wooteco/chess/util/JDBCConnector.java deleted file mode 100644 index 9933909e27..0000000000 --- a/src/main/java/wooteco/chess/util/JDBCConnector.java +++ /dev/null @@ -1,33 +0,0 @@ -package wooteco.chess.util; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -public class JDBCConnector { - private static final String server = "localhost:13306"; - private static final String database = "chess"; - private static final String option = "?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8"; - private static final String userName = "root"; - private static final String password = "root"; - - public static Connection getConnection() { - try { - Class.forName("com.mysql.cj.jdbc.Driver"); - } catch (ClassNotFoundException e) { - System.err.println("!! JDBC Driver load 오류 : " + e.getMessage()); - e.printStackTrace(); - } - - Connection con = null; - - try { - con = DriverManager.getConnection("jdbc:mysql://" + server + "/" + database + option, userName, password); - System.out.println("정상적으로 연결됐습니다."); - } catch (SQLException e) { - System.err.println("연결 오류 :" + e.getMessage()); - e.printStackTrace(); - } - return con; - } -} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 701bfc4705..b910304f44 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -3,5 +3,4 @@ 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 spring.datasource.password=root -required=필수항목입니다. server.error.whitelabel.enabled=false diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql new file mode 100644 index 0000000000..acc193b487 --- /dev/null +++ b/src/main/resources/schema.sql @@ -0,0 +1,17 @@ +create table room( + id uuid primary key, + name varchar(255) not null, + password varchar(20) not null +); + +create table game( + room uuid not null, + turn varchar(10) not null +); + +create table piece( + game uuid not null, + name varchar(20) not null, + color varchar(20) not null, + position varchar(20) not null +); \ No newline at end of file diff --git a/src/main/resources/templates/game.html b/src/main/resources/templates/game.html deleted file mode 100644 index 554717d8e9..0000000000 --- a/src/main/resources/templates/game.html +++ /dev/null @@ -1,339 +0,0 @@ - - - - - - - - - - - - -
-
-

가 이겼습니다!

-
-
- -
-

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

- -
현재 턴은 입니다.
- - - - - - - - - -
{{this.roomId}} {{this.roomName}}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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 6e354dbb6d..8382de0f85 100644 --- a/src/main/resources/templates/index.hbs +++ b/src/main/resources/templates/index.hbs @@ -35,7 +35,7 @@ {{#each rooms}} {{this.roomId}} - {{this.roomName}} + {{this.roomDto}} @@ -53,7 +53,7 @@
방을 만드려면 방 제목을 입력해주세요. - +
{{#if errors}} diff --git a/src/main/resources/templates/index.html b/src/main/resources/templates/index.html deleted file mode 100644 index 3f755100e1..0000000000 --- a/src/main/resources/templates/index.html +++ /dev/null @@ -1,84 +0,0 @@ - - - - - - - - - - - - -
-

전체 방 목록

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

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

- {{/if}} - - -
- 방을 만드려면 방 제목을 입력해주세요. - -
- - - -
-
- 방에 입장하려면 방 번호를 입력해주세요. - -
- -
-
- - - - - \ No newline at end of file From 2f8733ea81bbf48069f10f6f06d4e0143e130b58 Mon Sep 17 00:00:00 2001 From: dd Date: Wed, 29 Apr 2020 17:33:25 +0900 Subject: [PATCH 05/10] =?UTF-8?q?refactor=20:=20=EB=B3=80=EA=B2=BD=20?= =?UTF-8?q?=EC=82=AC=ED=95=AD=EC=97=90=20=EB=A7=9E=EA=B2=8C=20Controller?= =?UTF-8?q?=EC=99=80=20=EC=84=9C=EB=B9=84=EC=8A=A4=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../wooteco/chess/config/ModelConfig.java | 14 ----- .../controller/SpringGameController.java | 5 +- .../controller/SpringRoomController.java | 46 ++++++++++---- .../java/wooteco/chess/dto/AuthorizeDto.java | 26 ++++++++ .../wooteco/chess/dto/GameRequestDto.java | 8 +-- .../wooteco/chess/dto/MoveRequestDto.java | 8 +-- src/main/java/wooteco/chess/dto/RoomDto.java | 33 ---------- .../wooteco/chess/dto/RoomRequestDto.java | 24 ++++++++ .../wooteco/chess/dto/RoomResponseDto.java | 35 +++++++++++ .../chess/repository/GameRepository.java | 2 +- .../chess/repository/PieceRepository.java | 2 +- .../chess/repository/RoomRepository.java | 4 +- .../chess/repository/entity/GameEntity.java | 5 +- .../chess/repository/entity/PieceEntity.java | 3 +- .../chess/repository/entity/RoomEntity.java | 10 +-- .../chess/service/SpringGameService.java | 11 ++-- .../chess/service/SpringRoomService.java | 30 +++++---- src/main/resources/application.properties | 3 +- src/main/resources/schema.sql | 33 ++++++---- src/main/resources/templates/index.hbs | 61 ++++++++++++++----- 20 files changed, 229 insertions(+), 134 deletions(-) delete mode 100644 src/main/java/wooteco/chess/config/ModelConfig.java create mode 100644 src/main/java/wooteco/chess/dto/AuthorizeDto.java delete mode 100644 src/main/java/wooteco/chess/dto/RoomDto.java create mode 100644 src/main/java/wooteco/chess/dto/RoomRequestDto.java create mode 100644 src/main/java/wooteco/chess/dto/RoomResponseDto.java diff --git a/src/main/java/wooteco/chess/config/ModelConfig.java b/src/main/java/wooteco/chess/config/ModelConfig.java deleted file mode 100644 index faa109140f..0000000000 --- a/src/main/java/wooteco/chess/config/ModelConfig.java +++ /dev/null @@ -1,14 +0,0 @@ -package wooteco.chess.config; - -import org.modelmapper.ModelMapper; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class ModelConfig { - - @Bean - public ModelMapper modelMapper(){ - return new ModelMapper(); - } -} diff --git a/src/main/java/wooteco/chess/controller/SpringGameController.java b/src/main/java/wooteco/chess/controller/SpringGameController.java index 94afd20e7e..923e141b99 100644 --- a/src/main/java/wooteco/chess/controller/SpringGameController.java +++ b/src/main/java/wooteco/chess/controller/SpringGameController.java @@ -3,17 +3,14 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import wooteco.chess.domain.Color; import wooteco.chess.dto.GameRequestDto; import wooteco.chess.dto.GameResponseDto; import wooteco.chess.dto.GameStatusDto; import wooteco.chess.dto.MoveRequestDto; import wooteco.chess.service.SpringGameService; -import javax.servlet.http.HttpServletRequest; import java.sql.SQLException; import java.util.List; -import java.util.UUID; @RestController @RequestMapping("/game") @@ -47,7 +44,7 @@ public GameStatusDto showStatus(@RequestParam GameRequestDto gameRequestDto) thr } @GetMapping("/load") - public GameResponseDto load(@RequestParam UUID roomId) throws SQLException { + public GameResponseDto load(@RequestParam Long roomId) throws SQLException { return gameService.findAllPieces(roomId); } diff --git a/src/main/java/wooteco/chess/controller/SpringRoomController.java b/src/main/java/wooteco/chess/controller/SpringRoomController.java index 95063ec633..e11d07a4e5 100644 --- a/src/main/java/wooteco/chess/controller/SpringRoomController.java +++ b/src/main/java/wooteco/chess/controller/SpringRoomController.java @@ -2,11 +2,13 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import wooteco.chess.dto.RoomDto; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.ModelAndView; +import wooteco.chess.dto.AuthorizeDto; +import wooteco.chess.dto.RoomRequestDto; +import wooteco.chess.dto.RoomResponseDto; import wooteco.chess.service.SpringRoomService; import javax.validation.Valid; @@ -25,7 +27,7 @@ private SpringRoomController(final SpringRoomService roomService) { @GetMapping public String getAllRooms(Model model) throws SQLException { - List rooms = roomService.findAllRoom(); + List rooms = roomService.findAllRoom(); model.addAttribute("rooms", rooms); return "index"; @@ -38,19 +40,39 @@ public String enterRoom(@RequestParam(value = "roomId") Integer roomId, Model mo } // TODO: 2020/04/22 valid 에러페이지 이동 문제 - @GetMapping("/create") - public String createRoom(@Valid RoomDto roomId, Errors errors, Model model) throws SQLException { - if (errors.hasErrors()) { - model.addAttribute("errors", errors); + @PostMapping("/create") + public String createRoom(@Valid RoomRequestDto roomRequestDto, BindingResult bindingResult, Model model) throws SQLException { + if (bindingResult.hasErrors()) { + model.addAttribute("nameError", bindingResult.getFieldError("name")); + model.addAttribute("passwordError", bindingResult.getFieldError("password")); return getAllRooms(model); } - roomService.addRoom(roomId); + roomService.addRoom(roomRequestDto); return "redirect:/rooms"; } @GetMapping("/remove") - public String removeRoom(@RequestParam(value = "roomId") RoomDto roomDto) throws SQLException { - roomService.removeRoom(roomDto); + public String removeRoom(@RequestParam(value = "roomId") RoomResponseDto roomResponseDto) throws SQLException { + roomService.removeRoom(roomResponseDto); return "redirect:/rooms"; } + + @PostMapping("/authorize") + @ResponseBody + public boolean authorize(@Valid @RequestBody AuthorizeDto authorizeDto, Errors errors) { +// ModelAndView model = new ModelAndView("index"); +// +// if(errors.hasErrors()){ +// model.addObject("errors", errors); +// return model; +// } + return roomService.authorize(authorizeDto.getId(), authorizeDto.getPassword()); +// model.addObject("result", result); +// if (!result) { +// errors.rejectValue("password", "wrongPassword", "wrong Password"); +// model.addObject("authorizeError", errors.getFieldValue("password")); +// } +// return model; + + } } diff --git a/src/main/java/wooteco/chess/dto/AuthorizeDto.java b/src/main/java/wooteco/chess/dto/AuthorizeDto.java new file mode 100644 index 0000000000..23cbdfa1b6 --- /dev/null +++ b/src/main/java/wooteco/chess/dto/AuthorizeDto.java @@ -0,0 +1,26 @@ +package wooteco.chess.dto; + +import org.springframework.lang.NonNull; + +import javax.validation.constraints.NotEmpty; + +public class AuthorizeDto { + + private Long id; + + @NotEmpty + private String password; + + public AuthorizeDto(@NotEmpty final Long id, @NotEmpty final String password) { + this.id = id; + this.password = password; + } + + public Long getId() { + return id; + } + + public String getPassword() { + return password; + } +} diff --git a/src/main/java/wooteco/chess/dto/GameRequestDto.java b/src/main/java/wooteco/chess/dto/GameRequestDto.java index a63f75be15..3e4b904388 100644 --- a/src/main/java/wooteco/chess/dto/GameRequestDto.java +++ b/src/main/java/wooteco/chess/dto/GameRequestDto.java @@ -1,16 +1,14 @@ package wooteco.chess.dto; -import java.util.UUID; - public class GameRequestDto { - private UUID id; + private Long id; - public GameRequestDto(final UUID id) { + public GameRequestDto(final Long id) { this.id = id; } - public UUID getId() { + public Long getId() { return id; } } diff --git a/src/main/java/wooteco/chess/dto/MoveRequestDto.java b/src/main/java/wooteco/chess/dto/MoveRequestDto.java index a6b64428ad..40506f3f99 100644 --- a/src/main/java/wooteco/chess/dto/MoveRequestDto.java +++ b/src/main/java/wooteco/chess/dto/MoveRequestDto.java @@ -1,20 +1,18 @@ package wooteco.chess.dto; -import java.util.UUID; - public class MoveRequestDto { - private UUID id; + private Long id; private String sourcePosition; private String targetPosition; - public MoveRequestDto(final UUID id, final String sourcePosition, final String targetPosition) { + public MoveRequestDto(final Long id, final String sourcePosition, final String targetPosition) { this.id = id; this.sourcePosition = sourcePosition; this.targetPosition = targetPosition; } - public UUID getId() { + public Long getId() { return id; } diff --git a/src/main/java/wooteco/chess/dto/RoomDto.java b/src/main/java/wooteco/chess/dto/RoomDto.java deleted file mode 100644 index 4c1e161296..0000000000 --- a/src/main/java/wooteco/chess/dto/RoomDto.java +++ /dev/null @@ -1,33 +0,0 @@ -package wooteco.chess.dto; - -import javax.validation.constraints.NotEmpty; -import java.util.UUID; - -public class RoomDto { - - private UUID id; - - @NotEmpty - private String roomName; - - @NotEmpty - private String password; - - public RoomDto(@NotEmpty final UUID id, @NotEmpty final String roomName, @NotEmpty final String password) { - this.id = id; - this.roomName = roomName; - this.password = password; - } - - public UUID getId() { - return id; - } - - public String getRoomName() { - return roomName; - } - - public String getPassword() { - return password; - } -} diff --git a/src/main/java/wooteco/chess/dto/RoomRequestDto.java b/src/main/java/wooteco/chess/dto/RoomRequestDto.java new file mode 100644 index 0000000000..e4d5795a6f --- /dev/null +++ b/src/main/java/wooteco/chess/dto/RoomRequestDto.java @@ -0,0 +1,24 @@ +package wooteco.chess.dto; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + +public class RoomRequestDto { + @NotEmpty + private String name; + @NotEmpty + private String password; + + public RoomRequestDto(@NotEmpty final String name, @NotEmpty final String password) { + this.name = name; + this.password = password; + } + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } +} diff --git a/src/main/java/wooteco/chess/dto/RoomResponseDto.java b/src/main/java/wooteco/chess/dto/RoomResponseDto.java new file mode 100644 index 0000000000..d528d2762a --- /dev/null +++ b/src/main/java/wooteco/chess/dto/RoomResponseDto.java @@ -0,0 +1,35 @@ +package wooteco.chess.dto; + +import javax.validation.constraints.NotEmpty; + +public class RoomResponseDto { + + private Long id; + + @NotEmpty + private String name; + + @NotEmpty + private String password; + + private RoomResponseDto() { + } + + public RoomResponseDto(final Long id, @NotEmpty final String name, @NotEmpty final String password) { + this.id = id; + this.name = name; + this.password = password; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } +} diff --git a/src/main/java/wooteco/chess/repository/GameRepository.java b/src/main/java/wooteco/chess/repository/GameRepository.java index 75fea038cd..83da092a8c 100644 --- a/src/main/java/wooteco/chess/repository/GameRepository.java +++ b/src/main/java/wooteco/chess/repository/GameRepository.java @@ -5,5 +5,5 @@ import java.util.UUID; -public interface GameRepository extends CrudRepository { +public interface GameRepository extends CrudRepository { } diff --git a/src/main/java/wooteco/chess/repository/PieceRepository.java b/src/main/java/wooteco/chess/repository/PieceRepository.java index b031e2528c..4abbd9fae0 100644 --- a/src/main/java/wooteco/chess/repository/PieceRepository.java +++ b/src/main/java/wooteco/chess/repository/PieceRepository.java @@ -5,6 +5,6 @@ import java.util.UUID; -public interface PieceRepository extends CrudRepository { +public interface PieceRepository extends CrudRepository { } diff --git a/src/main/java/wooteco/chess/repository/RoomRepository.java b/src/main/java/wooteco/chess/repository/RoomRepository.java index 2dabeefbc2..cda7be6ae2 100644 --- a/src/main/java/wooteco/chess/repository/RoomRepository.java +++ b/src/main/java/wooteco/chess/repository/RoomRepository.java @@ -5,13 +5,13 @@ import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import wooteco.chess.domain.Color; +import wooteco.chess.repository.entity.GameEntity; import wooteco.chess.repository.entity.RoomEntity; import java.util.List; import java.util.UUID; -public interface RoomRepository extends CrudRepository { - +public interface RoomRepository extends CrudRepository { @Override List findAll(); } diff --git a/src/main/java/wooteco/chess/repository/entity/GameEntity.java b/src/main/java/wooteco/chess/repository/entity/GameEntity.java index aa14f7557f..d3cc211abd 100644 --- a/src/main/java/wooteco/chess/repository/entity/GameEntity.java +++ b/src/main/java/wooteco/chess/repository/entity/GameEntity.java @@ -1,15 +1,18 @@ package wooteco.chess.repository.entity; import org.springframework.data.annotation.Id; +import org.springframework.data.relational.core.mapping.Column; import org.springframework.data.relational.core.mapping.Table; import wooteco.chess.domain.Color; +import java.io.Serializable; import java.util.Set; import java.util.UUID; @Table("game") -public class GameEntity { +public class GameEntity implements Serializable { private Color turn; + @Column("game") private Set piece; public GameEntity(final Color turn, final Set piece) { diff --git a/src/main/java/wooteco/chess/repository/entity/PieceEntity.java b/src/main/java/wooteco/chess/repository/entity/PieceEntity.java index 09046833f6..caa63e7149 100644 --- a/src/main/java/wooteco/chess/repository/entity/PieceEntity.java +++ b/src/main/java/wooteco/chess/repository/entity/PieceEntity.java @@ -3,10 +3,11 @@ import org.springframework.data.annotation.Id; import org.springframework.data.relational.core.mapping.Table; +import java.io.Serializable; import java.util.UUID; @Table("piece") -public class PieceEntity { +public class PieceEntity implements Serializable { private String name; private String color; private String position; diff --git a/src/main/java/wooteco/chess/repository/entity/RoomEntity.java b/src/main/java/wooteco/chess/repository/entity/RoomEntity.java index 25e6196803..05c040518a 100644 --- a/src/main/java/wooteco/chess/repository/entity/RoomEntity.java +++ b/src/main/java/wooteco/chess/repository/entity/RoomEntity.java @@ -1,20 +1,14 @@ package wooteco.chess.repository.entity; import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.PersistenceConstructor; import org.springframework.data.relational.core.mapping.Column; import org.springframework.data.relational.core.mapping.Table; -import wooteco.chess.domain.Color; - -import javax.annotation.Generated; -import java.util.Set; -import java.util.UUID; @Table("room") public class RoomEntity { @Id - private UUID id; + private Long id; private String name; private String password; @Column(value = "room") @@ -26,7 +20,7 @@ public RoomEntity(final String name, final String password, final GameEntity gam this.game = game; } - public UUID getId() { + public Long getId() { return id; } diff --git a/src/main/java/wooteco/chess/service/SpringGameService.java b/src/main/java/wooteco/chess/service/SpringGameService.java index cb98275790..8e7096f697 100644 --- a/src/main/java/wooteco/chess/service/SpringGameService.java +++ b/src/main/java/wooteco/chess/service/SpringGameService.java @@ -6,8 +6,6 @@ import wooteco.chess.domain.piece.Piece; import wooteco.chess.domain.piece.PieceMapper; import wooteco.chess.dto.*; -import wooteco.chess.repository.GameRepository; -import wooteco.chess.repository.PieceRepository; import wooteco.chess.domain.Color; import wooteco.chess.domain.GameManager; import wooteco.chess.domain.PieceScore; @@ -22,7 +20,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.UUID; import java.util.stream.Collectors; @Service @@ -44,7 +41,7 @@ public GameResponseDto initialize(GameRequestDto request) throws SQLException { } public GameResponseDto move(MoveRequestDto moveRequestDto) throws SQLException { - UUID id = moveRequestDto.getId(); + Long id = moveRequestDto.getId(); String sourcePosition = moveRequestDto.getSourcePosition(); String targetPosition = moveRequestDto.getTargetPosition(); @@ -69,7 +66,7 @@ public GameResponseDto move(MoveRequestDto moveRequestDto) throws SQLException { } public double getScore(final GameRequestDto gameRequestDto) throws SQLException { - UUID id = gameRequestDto.getId(); + Long id = gameRequestDto.getId(); RoomEntity roomEntity = roomRepository.findById(id) .orElseThrow(RuntimeException::new); @@ -85,7 +82,7 @@ public double getScore(final GameRequestDto gameRequestDto) throws SQLException } public List getMovablePositions(final MoveRequestDto moveRequestDto) throws SQLException { - UUID id = moveRequestDto.getId(); + Long id = moveRequestDto.getId(); String sourcePosition = moveRequestDto.getSourcePosition(); RoomEntity roomEntity = roomRepository.findById(id) @@ -127,7 +124,7 @@ private Map convertPieceEntityToPieces(final Set e )); } - public GameResponseDto findAllPieces(final UUID roomId) { + public GameResponseDto findAllPieces(final Long roomId) { return convertRoomEntityToGameDto(roomRepository .findById(roomId) .orElseThrow(RuntimeException::new) diff --git a/src/main/java/wooteco/chess/service/SpringRoomService.java b/src/main/java/wooteco/chess/service/SpringRoomService.java index a14c460b28..30cd337908 100644 --- a/src/main/java/wooteco/chess/service/SpringRoomService.java +++ b/src/main/java/wooteco/chess/service/SpringRoomService.java @@ -1,13 +1,13 @@ package wooteco.chess.service; -import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import wooteco.chess.domain.Color; import wooteco.chess.domain.board.Position; import wooteco.chess.domain.piece.Piece; import wooteco.chess.domain.piece.Pieces; -import wooteco.chess.dto.RoomDto; +import wooteco.chess.dto.RoomRequestDto; +import wooteco.chess.dto.RoomResponseDto; import wooteco.chess.repository.RoomRepository; import wooteco.chess.repository.entity.GameEntity; import wooteco.chess.repository.entity.PieceEntity; @@ -25,27 +25,25 @@ public class SpringRoomService { @Autowired private RoomRepository roomRepository; - @Autowired - private ModelMapper modelMapper; - public void addRoom(RoomDto roomDto) throws SQLException { + public void addRoom(RoomRequestDto roomRequestDto) throws SQLException { Set pieceEntities = convertPiecesToPieceEntity(Pieces.initPieces()); GameEntity gameEntity = new GameEntity(Color.WHITE, pieceEntities); - roomRepository.save(new RoomEntity(roomDto.getRoomName(), roomDto.getPassword(), gameEntity)); + roomRepository.save(new RoomEntity(roomRequestDto.getName(), roomRequestDto.getPassword(), gameEntity)); } - public void removeRoom(RoomDto roomDto) throws SQLException { - roomRepository.deleteById(roomDto.getId()); + public void removeRoom(RoomResponseDto roomResponseDto) throws SQLException { + roomRepository.deleteById(roomResponseDto.getId()); } - public List findAllRoom() throws SQLException { + public List findAllRoom() throws SQLException { return convertRoomEntityToDto(roomRepository.findAll()); } - private List convertRoomEntityToDto(final List roomEntities) { + private List convertRoomEntityToDto(final List roomEntities) { return roomEntities.stream() - .map(roomEntity -> new RoomDto(roomEntity.getId(), roomEntity.getName(), roomEntity.getPassword())) + .map(roomEntity -> new RoomResponseDto(roomEntity.getId(), roomEntity.getName(), roomEntity.getPassword())) .collect(Collectors.toList()); } @@ -57,4 +55,14 @@ private Set convertPiecesToPieceEntity(final Map p entry.getKey().getPosition())) .collect(Collectors.toSet()); } + + public boolean authorize(final Long id, final String password) { + RoomEntity roomEntity = roomRepository.findById(id) + .orElseThrow(RuntimeException::new); + + if (password.equals(roomEntity.getPassword())) { + return true; + } + return false; + } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index b910304f44..4c07b6a587 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,6 +1,7 @@ -spring.h2.console.enabled=true +spring.h2.console.enabled=false 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 spring.datasource.password=root server.error.whitelabel.enabled=false +logging.level.org.springframework.jdbc.core.JdbcTemplate=debug diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql index acc193b487..e00ef14872 100644 --- a/src/main/resources/schema.sql +++ b/src/main/resources/schema.sql @@ -1,17 +1,26 @@ -create table room( - id uuid primary key, - name varchar(255) not null, - password varchar(20) not null +DROP TABLE IF EXISTS room ; +DROP TABLE IF EXISTS game ; +DROP TABLE IF EXISTS piece ; + +create table room +( + id bigint auto_increment not null + primary key, + name varchar(255) not null, + password varchar(20) not null ); -create table game( - room uuid not null, +create table piece +( + game bigint not null, + name varchar(20) not null, + color varchar(20) not null, + position varchar(20) not null +); + +create table game +( + room bigint not null, turn varchar(10) not null ); -create table piece( - game uuid not null, - name varchar(20) not null, - color varchar(20) not null, - position varchar(20) not null -); \ No newline at end of file diff --git a/src/main/resources/templates/index.hbs b/src/main/resources/templates/index.hbs index 8382de0f85..14ae7cbfb5 100644 --- a/src/main/resources/templates/index.hbs +++ b/src/main/resources/templates/index.hbs @@ -34,8 +34,8 @@ {{#each rooms}} - {{this.roomId}} - {{this.roomDto}} + {{this.id}} + {{this.name}} @@ -50,15 +50,23 @@

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

{{/if}} -
+
- 방을 만드려면 방 제목을 입력해주세요. - + 방을 만드려면 방 제목과 비밀번호를 입력해주세요. + +
- {{#if errors}} + {{#if nameError}}
방 제목은 한 글자 이상이어야 합니다.
{{/if}} + {{#if passwordError}} +
방 비밀번호는 한 글자 이상이어야 합니다.
+ {{/if}} + {{#if authorizeError}} +
비밀번호가 일치하지 않습니다.
+ {{/if}} +
@@ -68,29 +76,50 @@ for (let i = 0; i < allDeleteButton.length; i++) { allDeleteButton[i].addEventListener('click', function () { - let roomId = allDeleteButton[i].parentElement.parentElement.firstElementChild.innerHTML; - deleteRoom(roomId); + let id = allDeleteButton[i].parentElement.parentElement.firstElementChild.innerHTML; + deleteRoom(id); }); } for (let i = 0; i < allEnterButton.length; i++) { allEnterButton[i].addEventListener('click', function () { - let roomId = allEnterButton[i].parentElement.parentElement.firstElementChild.innerHTML; - enterRoom(roomId); + let id = allEnterButton[i].parentElement.parentElement.firstElementChild.innerHTML; + enterRoom(id); }); } - function deleteRoom(roomId) { - console.log("deleteRoom : " + roomId); + function deleteRoom(id) { + console.log("deleteRoom : " + id); let currentPath = window.location.pathname; - location.href = currentPath + '/remove?roomId=' + roomId; + location.href = currentPath + '/remove/' + names; } - function enterRoom(roomId) { - console.log("enterRoom : " + roomId); + function enterRoom(id) { + console.log("enterRoom : " + id); let currentPath = window.location.pathname; - location.href = currentPath + '/enter?roomId=' + roomId; + let inputPassword = prompt('비밀번호를 입력해주세요!'); + if(authorizePassword(id, inputPassword)) { + alert("통과됐습니다"); + } + // location.href = currentPath + '/enter/' + id; + } + + function authorizePassword(id, inputPassword) { + let data = { + id : id, + password : inputPassword + }; + + fetch("/rooms/authorize", { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(data), + }).then(response => response.json()){ + return response; + } } From aecc058f23fdd2070478c015d4cf6fc2123224bc Mon Sep 17 00:00:00 2001 From: aegis Date: Wed, 29 Apr 2020 18:45:27 +0900 Subject: [PATCH 06/10] =?UTF-8?q?refactor=20:=20=EA=B3=B5=EB=B0=B1=20?= =?UTF-8?q?=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../wooteco/chess/SpringChessApplication.java | 1 - .../chess/service/SpringGameService.java | 10 ++++---- .../chess/service/SpringRoomService.java | 25 +++++++++---------- src/main/resources/schema.sql | 23 +++++++---------- 4 files changed, 26 insertions(+), 33 deletions(-) diff --git a/src/main/java/wooteco/chess/SpringChessApplication.java b/src/main/java/wooteco/chess/SpringChessApplication.java index 2604f73ab2..5d721ff530 100644 --- a/src/main/java/wooteco/chess/SpringChessApplication.java +++ b/src/main/java/wooteco/chess/SpringChessApplication.java @@ -5,7 +5,6 @@ @SpringBootApplication public class SpringChessApplication { - public static void main(String[] args) { SpringApplication.run(SpringChessApplication.class, args); } diff --git a/src/main/java/wooteco/chess/service/SpringGameService.java b/src/main/java/wooteco/chess/service/SpringGameService.java index 8e7096f697..570c54c731 100644 --- a/src/main/java/wooteco/chess/service/SpringGameService.java +++ b/src/main/java/wooteco/chess/service/SpringGameService.java @@ -29,7 +29,7 @@ public class SpringGameService { private RoomRepository roomRepository; @Transactional - public GameResponseDto initialize(GameRequestDto request) throws SQLException { + public GameResponseDto initialize(GameRequestDto request) { RoomEntity roomEntity = roomRepository.findById(request.getId()) .orElseThrow(RuntimeException::new); Set pieceEntities = convertPiecesToPieceEntity(Pieces.initPieces()); @@ -40,7 +40,7 @@ public GameResponseDto initialize(GameRequestDto request) throws SQLException { return convertRoomEntityToGameDto(persistEntity); } - public GameResponseDto move(MoveRequestDto moveRequestDto) throws SQLException { + public GameResponseDto move(MoveRequestDto moveRequestDto) { Long id = moveRequestDto.getId(); String sourcePosition = moveRequestDto.getSourcePosition(); String targetPosition = moveRequestDto.getTargetPosition(); @@ -65,7 +65,7 @@ public GameResponseDto move(MoveRequestDto moveRequestDto) throws SQLException { return convertRoomEntityToGameDto(roomEntity); } - public double getScore(final GameRequestDto gameRequestDto) throws SQLException { + public double getScore(final GameRequestDto gameRequestDto) { Long id = gameRequestDto.getId(); RoomEntity roomEntity = roomRepository.findById(id) @@ -81,7 +81,7 @@ public double getScore(final GameRequestDto gameRequestDto) throws SQLException return PieceScore.calculateByColor(gameManager, gameEntity.getTurn()); } - public List getMovablePositions(final MoveRequestDto moveRequestDto) throws SQLException { + public List getMovablePositions(final MoveRequestDto moveRequestDto) { Long id = moveRequestDto.getId(); String sourcePosition = moveRequestDto.getSourcePosition(); @@ -130,4 +130,4 @@ public GameResponseDto findAllPieces(final Long roomId) { .orElseThrow(RuntimeException::new) ); } -} +} \ No newline at end of file diff --git a/src/main/java/wooteco/chess/service/SpringRoomService.java b/src/main/java/wooteco/chess/service/SpringRoomService.java index 30cd337908..dd6ef7a85b 100644 --- a/src/main/java/wooteco/chess/service/SpringRoomService.java +++ b/src/main/java/wooteco/chess/service/SpringRoomService.java @@ -2,6 +2,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; + import wooteco.chess.domain.Color; import wooteco.chess.domain.board.Position; import wooteco.chess.domain.piece.Piece; @@ -25,40 +26,38 @@ public class SpringRoomService { @Autowired private RoomRepository roomRepository; - - public void addRoom(RoomRequestDto roomRequestDto) throws SQLException { + public void addRoom(RoomRequestDto roomRequestDto) { Set pieceEntities = convertPiecesToPieceEntity(Pieces.initPieces()); GameEntity gameEntity = new GameEntity(Color.WHITE, pieceEntities); roomRepository.save(new RoomEntity(roomRequestDto.getName(), roomRequestDto.getPassword(), gameEntity)); } - public void removeRoom(RoomResponseDto roomResponseDto) throws SQLException { + public void removeRoom(RoomResponseDto roomResponseDto) { roomRepository.deleteById(roomResponseDto.getId()); } - public List findAllRoom() throws SQLException { + public List findAllRoom() { return convertRoomEntityToDto(roomRepository.findAll()); - } private List convertRoomEntityToDto(final List roomEntities) { return roomEntities.stream() - .map(roomEntity -> new RoomResponseDto(roomEntity.getId(), roomEntity.getName(), roomEntity.getPassword())) - .collect(Collectors.toList()); + .map(roomEntity -> new RoomResponseDto(roomEntity.getId(), roomEntity.getName(), roomEntity.getPassword())) + .collect(Collectors.toList()); } private Set convertPiecesToPieceEntity(final Map pieces) { return pieces.entrySet().stream() - .map(entry -> - new PieceEntity(entry.getValue().getSymbol(), - entry.getValue().getColor().name(), - entry.getKey().getPosition())) - .collect(Collectors.toSet()); + .map(entry -> + new PieceEntity(entry.getValue().getSymbol(), + entry.getValue().getColor().name(), + entry.getKey().getPosition())) + .collect(Collectors.toSet()); } public boolean authorize(final Long id, final String password) { RoomEntity roomEntity = roomRepository.findById(id) - .orElseThrow(RuntimeException::new); + .orElseThrow(RuntimeException::new); if (password.equals(roomEntity.getPassword())) { return true; diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql index e00ef14872..0fc680966d 100644 --- a/src/main/resources/schema.sql +++ b/src/main/resources/schema.sql @@ -2,25 +2,20 @@ DROP TABLE IF EXISTS room ; DROP TABLE IF EXISTS game ; DROP TABLE IF EXISTS piece ; -create table room -( - id bigint auto_increment not null - primary key, - name varchar(255) not null, +create table room ( + id bigint auto_increment not null primary key, + name varchar(255) not null, password varchar(20) not null ); -create table piece -( - game bigint not null, - name varchar(20) not null, - color varchar(20) not null, +create table piece ( + game bigint not null, + name varchar(20) not null, + color varchar(20) not null, position varchar(20) not null ); -create table game -( +create table game ( room bigint not null, turn varchar(10) not null -); - +); \ No newline at end of file From e6395b45951071420608e620fbd89896ced731de Mon Sep 17 00:00:00 2001 From: aegis Date: Thu, 30 Apr 2020 02:30:03 +0900 Subject: [PATCH 07/10] =?UTF-8?q?refactor=20:=20GameRequestDto=20=EC=97=90?= =?UTF-8?q?=20=EA=B8=B0=EB=B3=B8=20=EC=83=9D=EC=84=B1=EC=9E=90=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/wooteco/chess/dto/GameRequestDto.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/wooteco/chess/dto/GameRequestDto.java b/src/main/java/wooteco/chess/dto/GameRequestDto.java index 3e4b904388..43f2c1efaf 100644 --- a/src/main/java/wooteco/chess/dto/GameRequestDto.java +++ b/src/main/java/wooteco/chess/dto/GameRequestDto.java @@ -4,6 +4,9 @@ public class GameRequestDto { private Long id; + public GameRequestDto() { + } + public GameRequestDto(final Long id) { this.id = id; } From a62fe081abd2d0e030b6b3c77083009984baf862 Mon Sep 17 00:00:00 2001 From: aegis Date: Thu, 30 Apr 2020 02:33:42 +0900 Subject: [PATCH 08/10] =?UTF-8?q?refactor=20:=20HTTP=20=EB=A9=94=EC=84=9C?= =?UTF-8?q?=EB=93=9C=EC=97=90=20=EB=A7=9E=EA=B2=8C=20Mapping=20=EC=96=B4?= =?UTF-8?q?=EB=85=B8=ED=85=8C=EC=9D=B4=EC=85=98=20=EC=88=98=EC=A0=95,@Path?= =?UTF-8?q?Variable=20=EC=A0=81=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/SpringGameController.java | 48 ++++++++------- .../controller/SpringRoomController.java | 53 +++++++---------- .../chess/service/SpringGameService.java | 25 ++++---- .../chess/service/SpringRoomService.java | 15 +++-- src/main/resources/templates/game.hbs | 59 +++++++++++-------- src/main/resources/templates/index.hbs | 31 ++++++---- 6 files changed, 124 insertions(+), 107 deletions(-) diff --git a/src/main/java/wooteco/chess/controller/SpringGameController.java b/src/main/java/wooteco/chess/controller/SpringGameController.java index 923e141b99..e1ccee9ed4 100644 --- a/src/main/java/wooteco/chess/controller/SpringGameController.java +++ b/src/main/java/wooteco/chess/controller/SpringGameController.java @@ -1,17 +1,20 @@ package wooteco.chess.controller; +import java.util.List; + import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + import wooteco.chess.dto.GameRequestDto; import wooteco.chess.dto.GameResponseDto; import wooteco.chess.dto.GameStatusDto; import wooteco.chess.dto.MoveRequestDto; import wooteco.chess.service.SpringGameService; -import java.sql.SQLException; -import java.util.List; - @RestController @RequestMapping("/game") public class SpringGameController { @@ -22,34 +25,35 @@ public SpringGameController(final SpringGameService gameService) { this.gameService = gameService; } - @GetMapping("/init") - public GameResponseDto init(@RequestParam GameRequestDto gameRequestDto) throws SQLException { + @PostMapping("/init") + public GameResponseDto init(@RequestBody GameRequestDto gameRequestDto) { return gameService.initialize(gameRequestDto); } + @PostMapping("/status") + public GameStatusDto showStatus(@RequestBody GameRequestDto gameRequestDto) { + return new GameStatusDto(gameService.getScore(gameRequestDto), gameService.getScore(gameRequestDto)); + } + + @PostMapping("/getPath") + public List getMovablePositions(@RequestBody MoveRequestDto moveRequestDto) { + System.out.println(moveRequestDto); + return gameService.getMovablePositions(moveRequestDto); + } + @PostMapping("/move") - public ResponseEntity move(@RequestBody MoveRequestDto requestDTO) throws SQLException { + public ResponseEntity move(@RequestBody MoveRequestDto moveRequestDto) { try { - return ResponseEntity.status(HttpStatus.OK).body(gameService.move(requestDTO)); + return ResponseEntity.status(HttpStatus.OK).body(gameService.move(moveRequestDto)); } catch (IllegalArgumentException e) { - GameResponseDto gameResponseDTO = gameService.findAllPieces(requestDTO.getId()); + GameResponseDto gameResponseDTO = gameService.findAllPieces(moveRequestDto.getId()); gameResponseDTO.setErrorMessage(e.getMessage()); return ResponseEntity.status(HttpStatus.OK).body(gameResponseDTO); } } - @GetMapping("/status") - public GameStatusDto showStatus(@RequestParam GameRequestDto gameRequestDto) throws SQLException { - return new GameStatusDto(gameService.getScore(gameRequestDto), gameService.getScore(gameRequestDto)); - } - - @GetMapping("/load") - public GameResponseDto load(@RequestParam Long roomId) throws SQLException { - return gameService.findAllPieces(roomId); - } - - @GetMapping("/get") - public List getMovablePositions(final MoveRequestDto moveRequestDto) throws SQLException { - return gameService.getMovablePositions(moveRequestDto); + @PostMapping("/load") + public GameResponseDto load(@RequestBody GameRequestDto gameRequestDto) { + return gameService.findAllPieces(gameRequestDto.getId()); } } diff --git a/src/main/java/wooteco/chess/controller/SpringRoomController.java b/src/main/java/wooteco/chess/controller/SpringRoomController.java index e11d07a4e5..a5b0b408f1 100644 --- a/src/main/java/wooteco/chess/controller/SpringRoomController.java +++ b/src/main/java/wooteco/chess/controller/SpringRoomController.java @@ -1,20 +1,25 @@ package wooteco.chess.controller; +import java.util.List; + +import javax.validation.Valid; + import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; -import org.springframework.validation.Errors; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + import wooteco.chess.dto.AuthorizeDto; import wooteco.chess.dto.RoomRequestDto; import wooteco.chess.dto.RoomResponseDto; import wooteco.chess.service.SpringRoomService; -import javax.validation.Valid; -import java.sql.SQLException; -import java.util.List; - @Controller @RequestMapping("/rooms") public class SpringRoomController { @@ -25,23 +30,23 @@ private SpringRoomController(final SpringRoomService roomService) { this.roomService = roomService; } + // TODO: 2020/04/30 Room 목록을 동기방식이 아닌 비동기 방식으로 수정해야됨 @GetMapping - public String getAllRooms(Model model) throws SQLException { + public String getAllRooms(Model model) { List rooms = roomService.findAllRoom(); model.addAttribute("rooms", rooms); return "index"; } - @GetMapping("/enter") - public String enterRoom(@RequestParam(value = "roomId") Integer roomId, Model model) { - model.addAttribute("roomId", roomId); + @GetMapping("/enter/{id}") + public String enterRoom(@PathVariable Long id, Model model) { + model.addAttribute("id", id); return "game"; } - // TODO: 2020/04/22 valid 에러페이지 이동 문제 @PostMapping("/create") - public String createRoom(@Valid RoomRequestDto roomRequestDto, BindingResult bindingResult, Model model) throws SQLException { + public String createRoom(@Valid RoomRequestDto roomRequestDto, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { model.addAttribute("nameError", bindingResult.getFieldError("name")); model.addAttribute("passwordError", bindingResult.getFieldError("password")); @@ -51,28 +56,14 @@ public String createRoom(@Valid RoomRequestDto roomRequestDto, BindingResult bin return "redirect:/rooms"; } - @GetMapping("/remove") - public String removeRoom(@RequestParam(value = "roomId") RoomResponseDto roomResponseDto) throws SQLException { - roomService.removeRoom(roomResponseDto); - return "redirect:/rooms"; + @DeleteMapping("/remove/{id}") + public void removeRoom(@PathVariable Long id) { + roomService.removeRoom(id); } @PostMapping("/authorize") @ResponseBody - public boolean authorize(@Valid @RequestBody AuthorizeDto authorizeDto, Errors errors) { -// ModelAndView model = new ModelAndView("index"); -// -// if(errors.hasErrors()){ -// model.addObject("errors", errors); -// return model; -// } + public boolean authorize(@Valid @RequestBody AuthorizeDto authorizeDto) { return roomService.authorize(authorizeDto.getId(), authorizeDto.getPassword()); -// model.addObject("result", result); -// if (!result) { -// errors.rejectValue("password", "wrongPassword", "wrong Password"); -// model.addObject("authorizeError", errors.getFieldValue("password")); -// } -// return model; - } } diff --git a/src/main/java/wooteco/chess/service/SpringGameService.java b/src/main/java/wooteco/chess/service/SpringGameService.java index 570c54c731..4989085371 100644 --- a/src/main/java/wooteco/chess/service/SpringGameService.java +++ b/src/main/java/wooteco/chess/service/SpringGameService.java @@ -1,27 +1,30 @@ package wooteco.chess.service; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import wooteco.chess.domain.piece.Piece; -import wooteco.chess.domain.piece.PieceMapper; -import wooteco.chess.dto.*; + 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.Piece; +import wooteco.chess.domain.piece.PieceMapper; import wooteco.chess.domain.piece.Pieces; +import wooteco.chess.dto.GameRequestDto; +import wooteco.chess.dto.GameResponseDto; +import wooteco.chess.dto.MoveRequestDto; +import wooteco.chess.dto.PiecesResponseDto; import wooteco.chess.repository.RoomRepository; import wooteco.chess.repository.entity.GameEntity; import wooteco.chess.repository.entity.PieceEntity; import wooteco.chess.repository.entity.RoomEntity; -import java.sql.SQLException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - @Service public class SpringGameService { @@ -124,9 +127,9 @@ private Map convertPieceEntityToPieces(final Set e )); } - public GameResponseDto findAllPieces(final Long roomId) { + public GameResponseDto findAllPieces(final Long id) { return convertRoomEntityToGameDto(roomRepository - .findById(roomId) + .findById(id) .orElseThrow(RuntimeException::new) ); } diff --git a/src/main/java/wooteco/chess/service/SpringRoomService.java b/src/main/java/wooteco/chess/service/SpringRoomService.java index dd6ef7a85b..518a1f17ec 100644 --- a/src/main/java/wooteco/chess/service/SpringRoomService.java +++ b/src/main/java/wooteco/chess/service/SpringRoomService.java @@ -1,5 +1,10 @@ package wooteco.chess.service; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -14,12 +19,6 @@ import wooteco.chess.repository.entity.PieceEntity; import wooteco.chess.repository.entity.RoomEntity; -import java.sql.SQLException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - @Service public class SpringRoomService { @@ -32,8 +31,8 @@ public void addRoom(RoomRequestDto roomRequestDto) { roomRepository.save(new RoomEntity(roomRequestDto.getName(), roomRequestDto.getPassword(), gameEntity)); } - public void removeRoom(RoomResponseDto roomResponseDto) { - roomRepository.deleteById(roomResponseDto.getId()); + public void removeRoom(Long id) { + roomRepository.deleteById(id); } public List findAllRoom() { diff --git a/src/main/resources/templates/game.hbs b/src/main/resources/templates/game.hbs index e904598bd4..7d528d940a 100644 --- a/src/main/resources/templates/game.hbs +++ b/src/main/resources/templates/game.hbs @@ -24,8 +24,8 @@
- -

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

+ +

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

현재 턴은 입니다.
@@ -140,9 +140,12 @@ \ No newline at end of file From b37df4c9f737d695154cb7057b0bfcf8fc3934d6 Mon Sep 17 00:00:00 2001 From: aegis Date: Thu, 30 Apr 2020 02:33:42 +0900 Subject: [PATCH 09/10] =?UTF-8?q?refactor=20:=20HTTP=20=EB=A9=94=EC=84=9C?= =?UTF-8?q?=EB=93=9C=EC=97=90=20=EB=A7=9E=EA=B2=8C=20Mapping=20=EC=96=B4?= =?UTF-8?q?=EB=85=B8=ED=85=8C=EC=9D=B4=EC=85=98=20=EC=88=98=EC=A0=95,@Path?= =?UTF-8?q?Variable=20=EC=A0=81=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 1 - .../controller/SpringGameController.java | 48 ++++++++------- .../controller/SpringRoomController.java | 53 +++++++---------- .../chess/service/SpringGameService.java | 25 ++++---- .../chess/service/SpringRoomService.java | 15 +++-- src/main/resources/templates/game.hbs | 59 +++++++++++-------- src/main/resources/templates/index.hbs | 31 ++++++---- 7 files changed, 124 insertions(+), 108 deletions(-) diff --git a/build.gradle b/build.gradle index 5e26eea49d..ddf894cb22 100644 --- a/build.gradle +++ b/build.gradle @@ -14,7 +14,6 @@ repositories { dependencies { compile('mysql:mysql-connector-java:8.0.16') - compile group: 'org.modelmapper', name: 'modelmapper', version: '2.3.7' implementation 'com.sparkjava:spark-core:2.9.0' implementation 'com.sparkjava:spark-template-handlebars:2.7.1' implementation 'org.springframework.boot:spring-boot-starter-web' diff --git a/src/main/java/wooteco/chess/controller/SpringGameController.java b/src/main/java/wooteco/chess/controller/SpringGameController.java index 923e141b99..e1ccee9ed4 100644 --- a/src/main/java/wooteco/chess/controller/SpringGameController.java +++ b/src/main/java/wooteco/chess/controller/SpringGameController.java @@ -1,17 +1,20 @@ package wooteco.chess.controller; +import java.util.List; + import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + import wooteco.chess.dto.GameRequestDto; import wooteco.chess.dto.GameResponseDto; import wooteco.chess.dto.GameStatusDto; import wooteco.chess.dto.MoveRequestDto; import wooteco.chess.service.SpringGameService; -import java.sql.SQLException; -import java.util.List; - @RestController @RequestMapping("/game") public class SpringGameController { @@ -22,34 +25,35 @@ public SpringGameController(final SpringGameService gameService) { this.gameService = gameService; } - @GetMapping("/init") - public GameResponseDto init(@RequestParam GameRequestDto gameRequestDto) throws SQLException { + @PostMapping("/init") + public GameResponseDto init(@RequestBody GameRequestDto gameRequestDto) { return gameService.initialize(gameRequestDto); } + @PostMapping("/status") + public GameStatusDto showStatus(@RequestBody GameRequestDto gameRequestDto) { + return new GameStatusDto(gameService.getScore(gameRequestDto), gameService.getScore(gameRequestDto)); + } + + @PostMapping("/getPath") + public List getMovablePositions(@RequestBody MoveRequestDto moveRequestDto) { + System.out.println(moveRequestDto); + return gameService.getMovablePositions(moveRequestDto); + } + @PostMapping("/move") - public ResponseEntity move(@RequestBody MoveRequestDto requestDTO) throws SQLException { + public ResponseEntity move(@RequestBody MoveRequestDto moveRequestDto) { try { - return ResponseEntity.status(HttpStatus.OK).body(gameService.move(requestDTO)); + return ResponseEntity.status(HttpStatus.OK).body(gameService.move(moveRequestDto)); } catch (IllegalArgumentException e) { - GameResponseDto gameResponseDTO = gameService.findAllPieces(requestDTO.getId()); + GameResponseDto gameResponseDTO = gameService.findAllPieces(moveRequestDto.getId()); gameResponseDTO.setErrorMessage(e.getMessage()); return ResponseEntity.status(HttpStatus.OK).body(gameResponseDTO); } } - @GetMapping("/status") - public GameStatusDto showStatus(@RequestParam GameRequestDto gameRequestDto) throws SQLException { - return new GameStatusDto(gameService.getScore(gameRequestDto), gameService.getScore(gameRequestDto)); - } - - @GetMapping("/load") - public GameResponseDto load(@RequestParam Long roomId) throws SQLException { - return gameService.findAllPieces(roomId); - } - - @GetMapping("/get") - public List getMovablePositions(final MoveRequestDto moveRequestDto) throws SQLException { - return gameService.getMovablePositions(moveRequestDto); + @PostMapping("/load") + public GameResponseDto load(@RequestBody GameRequestDto gameRequestDto) { + return gameService.findAllPieces(gameRequestDto.getId()); } } diff --git a/src/main/java/wooteco/chess/controller/SpringRoomController.java b/src/main/java/wooteco/chess/controller/SpringRoomController.java index e11d07a4e5..a5b0b408f1 100644 --- a/src/main/java/wooteco/chess/controller/SpringRoomController.java +++ b/src/main/java/wooteco/chess/controller/SpringRoomController.java @@ -1,20 +1,25 @@ package wooteco.chess.controller; +import java.util.List; + +import javax.validation.Valid; + import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; -import org.springframework.validation.Errors; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + import wooteco.chess.dto.AuthorizeDto; import wooteco.chess.dto.RoomRequestDto; import wooteco.chess.dto.RoomResponseDto; import wooteco.chess.service.SpringRoomService; -import javax.validation.Valid; -import java.sql.SQLException; -import java.util.List; - @Controller @RequestMapping("/rooms") public class SpringRoomController { @@ -25,23 +30,23 @@ private SpringRoomController(final SpringRoomService roomService) { this.roomService = roomService; } + // TODO: 2020/04/30 Room 목록을 동기방식이 아닌 비동기 방식으로 수정해야됨 @GetMapping - public String getAllRooms(Model model) throws SQLException { + public String getAllRooms(Model model) { List rooms = roomService.findAllRoom(); model.addAttribute("rooms", rooms); return "index"; } - @GetMapping("/enter") - public String enterRoom(@RequestParam(value = "roomId") Integer roomId, Model model) { - model.addAttribute("roomId", roomId); + @GetMapping("/enter/{id}") + public String enterRoom(@PathVariable Long id, Model model) { + model.addAttribute("id", id); return "game"; } - // TODO: 2020/04/22 valid 에러페이지 이동 문제 @PostMapping("/create") - public String createRoom(@Valid RoomRequestDto roomRequestDto, BindingResult bindingResult, Model model) throws SQLException { + public String createRoom(@Valid RoomRequestDto roomRequestDto, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { model.addAttribute("nameError", bindingResult.getFieldError("name")); model.addAttribute("passwordError", bindingResult.getFieldError("password")); @@ -51,28 +56,14 @@ public String createRoom(@Valid RoomRequestDto roomRequestDto, BindingResult bin return "redirect:/rooms"; } - @GetMapping("/remove") - public String removeRoom(@RequestParam(value = "roomId") RoomResponseDto roomResponseDto) throws SQLException { - roomService.removeRoom(roomResponseDto); - return "redirect:/rooms"; + @DeleteMapping("/remove/{id}") + public void removeRoom(@PathVariable Long id) { + roomService.removeRoom(id); } @PostMapping("/authorize") @ResponseBody - public boolean authorize(@Valid @RequestBody AuthorizeDto authorizeDto, Errors errors) { -// ModelAndView model = new ModelAndView("index"); -// -// if(errors.hasErrors()){ -// model.addObject("errors", errors); -// return model; -// } + public boolean authorize(@Valid @RequestBody AuthorizeDto authorizeDto) { return roomService.authorize(authorizeDto.getId(), authorizeDto.getPassword()); -// model.addObject("result", result); -// if (!result) { -// errors.rejectValue("password", "wrongPassword", "wrong Password"); -// model.addObject("authorizeError", errors.getFieldValue("password")); -// } -// return model; - } } diff --git a/src/main/java/wooteco/chess/service/SpringGameService.java b/src/main/java/wooteco/chess/service/SpringGameService.java index 570c54c731..4989085371 100644 --- a/src/main/java/wooteco/chess/service/SpringGameService.java +++ b/src/main/java/wooteco/chess/service/SpringGameService.java @@ -1,27 +1,30 @@ package wooteco.chess.service; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import wooteco.chess.domain.piece.Piece; -import wooteco.chess.domain.piece.PieceMapper; -import wooteco.chess.dto.*; + 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.Piece; +import wooteco.chess.domain.piece.PieceMapper; import wooteco.chess.domain.piece.Pieces; +import wooteco.chess.dto.GameRequestDto; +import wooteco.chess.dto.GameResponseDto; +import wooteco.chess.dto.MoveRequestDto; +import wooteco.chess.dto.PiecesResponseDto; import wooteco.chess.repository.RoomRepository; import wooteco.chess.repository.entity.GameEntity; import wooteco.chess.repository.entity.PieceEntity; import wooteco.chess.repository.entity.RoomEntity; -import java.sql.SQLException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - @Service public class SpringGameService { @@ -124,9 +127,9 @@ private Map convertPieceEntityToPieces(final Set e )); } - public GameResponseDto findAllPieces(final Long roomId) { + public GameResponseDto findAllPieces(final Long id) { return convertRoomEntityToGameDto(roomRepository - .findById(roomId) + .findById(id) .orElseThrow(RuntimeException::new) ); } diff --git a/src/main/java/wooteco/chess/service/SpringRoomService.java b/src/main/java/wooteco/chess/service/SpringRoomService.java index dd6ef7a85b..518a1f17ec 100644 --- a/src/main/java/wooteco/chess/service/SpringRoomService.java +++ b/src/main/java/wooteco/chess/service/SpringRoomService.java @@ -1,5 +1,10 @@ package wooteco.chess.service; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -14,12 +19,6 @@ import wooteco.chess.repository.entity.PieceEntity; import wooteco.chess.repository.entity.RoomEntity; -import java.sql.SQLException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - @Service public class SpringRoomService { @@ -32,8 +31,8 @@ public void addRoom(RoomRequestDto roomRequestDto) { roomRepository.save(new RoomEntity(roomRequestDto.getName(), roomRequestDto.getPassword(), gameEntity)); } - public void removeRoom(RoomResponseDto roomResponseDto) { - roomRepository.deleteById(roomResponseDto.getId()); + public void removeRoom(Long id) { + roomRepository.deleteById(id); } public List findAllRoom() { diff --git a/src/main/resources/templates/game.hbs b/src/main/resources/templates/game.hbs index e904598bd4..7d528d940a 100644 --- a/src/main/resources/templates/game.hbs +++ b/src/main/resources/templates/game.hbs @@ -24,8 +24,8 @@
- -

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

+ +

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

현재 턴은 입니다.
@@ -140,9 +140,12 @@ \ No newline at end of file From 64ad0c55477e20f9799d971c64f69ddd90e9bb9d Mon Sep 17 00:00:00 2001 From: aegis Date: Fri, 1 May 2020 17:02:07 +0900 Subject: [PATCH 10/10] =?UTF-8?q?refactor=20:=20getPath=20=EC=9D=B4?= =?UTF-8?q?=EB=A6=84=EC=9D=84=20path=EB=A1=9C=20=EC=88=98=EC=A0=95,=20del?= =?UTF-8?q?=20:=20GameRepository,=20PieceRepository?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../wooteco/chess/controller/SpringGameController.java | 2 +- .../java/wooteco/chess/repository/GameRepository.java | 9 --------- .../java/wooteco/chess/repository/PieceRepository.java | 10 ---------- src/main/resources/templates/game.hbs | 2 +- 4 files changed, 2 insertions(+), 21 deletions(-) delete mode 100644 src/main/java/wooteco/chess/repository/GameRepository.java delete mode 100644 src/main/java/wooteco/chess/repository/PieceRepository.java diff --git a/src/main/java/wooteco/chess/controller/SpringGameController.java b/src/main/java/wooteco/chess/controller/SpringGameController.java index e1ccee9ed4..f2a5747505 100644 --- a/src/main/java/wooteco/chess/controller/SpringGameController.java +++ b/src/main/java/wooteco/chess/controller/SpringGameController.java @@ -35,7 +35,7 @@ public GameStatusDto showStatus(@RequestBody GameRequestDto gameRequestDto) { return new GameStatusDto(gameService.getScore(gameRequestDto), gameService.getScore(gameRequestDto)); } - @PostMapping("/getPath") + @PostMapping("/path") public List getMovablePositions(@RequestBody MoveRequestDto moveRequestDto) { System.out.println(moveRequestDto); return gameService.getMovablePositions(moveRequestDto); diff --git a/src/main/java/wooteco/chess/repository/GameRepository.java b/src/main/java/wooteco/chess/repository/GameRepository.java deleted file mode 100644 index 83da092a8c..0000000000 --- a/src/main/java/wooteco/chess/repository/GameRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package wooteco.chess.repository; - -import org.springframework.data.repository.CrudRepository; -import wooteco.chess.repository.entity.GameEntity; - -import java.util.UUID; - -public interface GameRepository extends CrudRepository { -} diff --git a/src/main/java/wooteco/chess/repository/PieceRepository.java b/src/main/java/wooteco/chess/repository/PieceRepository.java deleted file mode 100644 index 4abbd9fae0..0000000000 --- a/src/main/java/wooteco/chess/repository/PieceRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package wooteco.chess.repository; - -import org.springframework.data.repository.CrudRepository; -import wooteco.chess.repository.entity.PieceEntity; - -import java.util.UUID; - -public interface PieceRepository extends CrudRepository { - -} diff --git a/src/main/resources/templates/game.hbs b/src/main/resources/templates/game.hbs index 7d528d940a..b82cc1af23 100644 --- a/src/main/resources/templates/game.hbs +++ b/src/main/resources/templates/game.hbs @@ -253,7 +253,7 @@ id: {{id}}, sourcePosition: sourcePosition }; - xhr.open('POST', '/game/getPath', true); + xhr.open('POST', '/game/path', true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify(data)); }