From 31cfa7be6248c016777916112046e0ff7d1bb3b1 Mon Sep 17 00:00:00 2001 From: toneyparky Date: Wed, 29 Apr 2020 11:58:39 +0900 Subject: [PATCH 01/22] =?UTF-8?q?docs:=20README.md=20=EC=88=98=EC=A0=95=20?= =?UTF-8?q?-=20=EB=A0=88=EB=B2=A8=204?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0aa07befc8..73f9d62b32 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,34 @@ # 체스 3단계 - Spring Data JDBC 적용하기 ## **프로그래밍 요구사항** -- Spring Data JDBC를 활용하여 기존에 사용하던 DB에 접근하기 +- Spring Data JDBC를 활용하여 기존에 사용하던 DB에 접근하기. - 엔티티 클래스를 만들어 DB 테이블과 맵핑한다. -- Spring Data JDBC에서 제공하는 Repository를 활용하여 DB에 접근한다. \ No newline at end of file +- Spring Data JDBC에서 제공하는 Repository를 활용하여 DB에 접근한다. + +# 체스 4단계 - 동시에 여러 게임 하기 + +## **프로그래밍 요구사항** +- 체스 게임을 진행할 수 있는 방을 만들어서 동시에 여러 게임이 가능하도록 하기. + +### 체스방 만들기 + +- localhost:8080 요청 시 노출되는 페이지에 체스방을 만들 수 있는 버튼이 있다. +- 체스방 이름 입력하기 input을 추가한다. +- 체스방 만들기 버튼을 누르면 새로운 체스판이 초기화 된다. +- 체스방에는 고유식별값이 랜덤으로 부여된다. + +### 체스방 목록 조회하기 + +- localhost:8080 요청 시 체스방 목록을 조회할 수 있다 +- 체스방 목록에는 체스방 제목이 표시된다. +- 방법은 '/'로 GET 요청을 보내면 체스방에 대한 JSON이 반환된다. +- 그리고 해당 JSON을 index.js에서 처리하여 보여준다. + +### 체스방 참여하기 + +- localhost:8080 요청 시 체스방 목록에서 체스방을 클릭하면 체스 게임을 이어서 진행할 수 있다. + +### 엔티티 + +- Game : id(auto increment), UUID, name, canContinue +- History : id, start, end, gameId \ No newline at end of file From 1839c71ffb159eba9609ea85994bad61a85f9eef Mon Sep 17 00:00:00 2001 From: toneyparky Date: Wed, 29 Apr 2020 12:08:09 +0900 Subject: [PATCH 02/22] =?UTF-8?q?feat:=20=EB=8D=B0=EC=9D=B4=ED=84=B0?= =?UTF-8?q?=EB=B2=A0=EC=9D=B4=EC=8A=A4=20=EC=8A=A4=ED=82=A4=EB=A7=88=20?= =?UTF-8?q?=EC=97=85=EB=8D=B0=EC=9D=B4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit schema.sql 에 game 테이블 정보 추가, history 테이블과 game 테이블 연결 --- src/main/resources/schema.sql | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql index 5de8649aba..5421030f59 100644 --- a/src/main/resources/schema.sql +++ b/src/main/resources/schema.sql @@ -1,6 +1,16 @@ +create table game ( + id bigint not null auto_increment, + uuid varchar(36) not null, + name varchar(255) not null, + can_continue tinyint(1) default 1 not null, + primary key(id) +); + create table history ( id bigint not null auto_increment, start varchar(2) not null, end varchar(2) not null, - primary key(id) + game_id bigint not null, + primary key(id), + foreign key(game_id) references game(id) ); \ No newline at end of file From c8c9d31ff3ef3c8335902762dfb91150965f79bd Mon Sep 17 00:00:00 2001 From: toneyparky Date: Wed, 29 Apr 2020 12:11:26 +0900 Subject: [PATCH 03/22] =?UTF-8?q?feat:=20=ED=85=8C=EC=8A=A4=ED=8A=B8?= =?UTF-8?q?=EC=9A=A9=20=EB=8D=B0=EC=9D=B4=ED=84=B0=EB=B2=A0=EC=9D=B4?= =?UTF-8?q?=EC=8A=A4=20=EC=84=A4=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit application.properties test의 resources 디렉토리에 생성, h2 사용 --- src/test/resouces/application.properties | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 src/test/resouces/application.properties diff --git a/src/test/resouces/application.properties b/src/test/resouces/application.properties new file mode 100644 index 0000000000..bec9d9b83d --- /dev/null +++ b/src/test/resouces/application.properties @@ -0,0 +1,3 @@ +spring.h2.console.enabled=true +logging.level.org.springframework.jdbc=TRACE +spring.datasource.initialization-mode=ALWAYS From d332025ef85ee036470f07596ccc730b3a6cfc47 Mon Sep 17 00:00:00 2001 From: toneyparky Date: Wed, 29 Apr 2020 13:23:03 +0900 Subject: [PATCH 04/22] =?UTF-8?q?feat:=20=EA=B2=8C=EC=9E=84=20=EC=83=9D?= =?UTF-8?q?=EC=84=B1=20=ED=9B=84=20DB=EC=97=90=20=EC=A0=80=EC=9E=A5=20?= =?UTF-8?q?=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Game entity 생성 schema.sql 테이블이 없는 경우에만 생성하도록 변경 GameRepositoryTest 테스트 코드 추가 --- src/main/java/wooteco/chess/entity/Game.java | 50 +++++++++++++++++++ .../wooteco/chess/entity/GameRepository.java | 8 +++ src/main/resources/schema.sql | 6 +-- .../chess/entity/GameRepositoryTest.java | 34 +++++++++++++ 4 files changed, 95 insertions(+), 3 deletions(-) create mode 100644 src/main/java/wooteco/chess/entity/Game.java create mode 100644 src/main/java/wooteco/chess/entity/GameRepository.java create mode 100644 src/test/java/wooteco/chess/entity/GameRepositoryTest.java diff --git a/src/main/java/wooteco/chess/entity/Game.java b/src/main/java/wooteco/chess/entity/Game.java new file mode 100644 index 0000000000..aa5639e41c --- /dev/null +++ b/src/main/java/wooteco/chess/entity/Game.java @@ -0,0 +1,50 @@ +package wooteco.chess.entity; + +import org.springframework.data.annotation.Id; +import org.springframework.data.relational.core.mapping.Column; +import org.springframework.data.relational.core.mapping.Table; + +@Table("game") +public class Game { + private @Id Long id; + private @Column("name") String name; + private @Column("uuid") String uuid; + private @Column("can_continue") Boolean canContinue; + + public Game() { + } + + public Game(String name, String uuid) { + this.name = name; + this.uuid = uuid; + } + + public Game(Long id, String name, String uuid, Boolean canContinue) { + this.id = id; + this.name = name; + this.uuid = uuid; + this.canContinue = canContinue; + } + + public Game(String gameName, String uuid, Boolean i) { + this.name = gameName; + this.uuid = uuid; + this.canContinue = i; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getUuid() { + return uuid; + } + + public Boolean getCanContinue() { + return canContinue; + } +} diff --git a/src/main/java/wooteco/chess/entity/GameRepository.java b/src/main/java/wooteco/chess/entity/GameRepository.java new file mode 100644 index 0000000000..ae37145308 --- /dev/null +++ b/src/main/java/wooteco/chess/entity/GameRepository.java @@ -0,0 +1,8 @@ +package wooteco.chess.entity; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface GameRepository extends CrudRepository { +} diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql index 5421030f59..67fca8ef3d 100644 --- a/src/main/resources/schema.sql +++ b/src/main/resources/schema.sql @@ -1,12 +1,12 @@ -create table game ( +create table if NOT EXISTS game ( id bigint not null auto_increment, uuid varchar(36) not null, name varchar(255) not null, - can_continue tinyint(1) default 1 not null, + can_continue tinyint(1) not null, primary key(id) ); -create table history ( +create table if NOT EXISTS history ( id bigint not null auto_increment, start varchar(2) not null, end varchar(2) not null, diff --git a/src/test/java/wooteco/chess/entity/GameRepositoryTest.java b/src/test/java/wooteco/chess/entity/GameRepositoryTest.java new file mode 100644 index 0000000000..30f2a02620 --- /dev/null +++ b/src/test/java/wooteco/chess/entity/GameRepositoryTest.java @@ -0,0 +1,34 @@ +package wooteco.chess.entity; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.transaction.annotation.Transactional; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(SpringExtension.class) +@DataJdbcTest +@Transactional +class GameRepositoryTest { + + @Autowired + private GameRepository gameRepository; + + @DisplayName("save 새 게임 시작시 게임정보 저장 테스트") + @Test + void save_normal_test() { + String gameName = "first game"; + String uuid = "1q2w3e4r5t6y7u8i9o0p1q2w32e4t5y5u"; + + Game game = gameRepository.save(new Game(gameName, uuid, true)); + + assertThat(game.getId()).isEqualTo(1); + assertThat(game.getName()).isEqualTo(gameName); + assertThat(game.getUuid()).isEqualTo(uuid); + assertThat(game.getCanContinue()).isEqualTo(true); + } +} \ No newline at end of file From 520568e577bb50201fe3b97c817ae0fe99455611 Mon Sep 17 00:00:00 2001 From: toneyparky Date: Wed, 29 Apr 2020 13:45:00 +0900 Subject: [PATCH 05/22] =?UTF-8?q?feat:=20=EA=B2=8C=EC=9E=84=20DB=EC=97=90?= =?UTF-8?q?=20=EC=A1=B0=ED=9A=8C=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GameRepository findAll() 오버라이드 GameRepositoryTest 조회 테스트 작성 Game Equals 오버라이드 --- src/main/java/wooteco/chess/entity/Game.java | 26 +++++++++++++++++-- .../wooteco/chess/entity/GameRepository.java | 4 +++ .../chess/entity/GameRepositoryTest.java | 22 ++++++++++++++-- 3 files changed, 48 insertions(+), 4 deletions(-) diff --git a/src/main/java/wooteco/chess/entity/Game.java b/src/main/java/wooteco/chess/entity/Game.java index aa5639e41c..b53f639aa2 100644 --- a/src/main/java/wooteco/chess/entity/Game.java +++ b/src/main/java/wooteco/chess/entity/Game.java @@ -4,6 +4,8 @@ import org.springframework.data.relational.core.mapping.Column; import org.springframework.data.relational.core.mapping.Table; +import java.util.Objects; + @Table("game") public class Game { private @Id Long id; @@ -26,10 +28,10 @@ public Game(Long id, String name, String uuid, Boolean canContinue) { this.canContinue = canContinue; } - public Game(String gameName, String uuid, Boolean i) { + public Game(String gameName, String uuid, Boolean canContinue) { this.name = gameName; this.uuid = uuid; - this.canContinue = i; + this.canContinue = canContinue; } public Long getId() { @@ -47,4 +49,24 @@ public String getUuid() { public Boolean getCanContinue() { return canContinue; } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Game game = (Game) o; + return Objects.equals(id, game.id) && + Objects.equals(name, game.name) && + Objects.equals(uuid, game.uuid) && + Objects.equals(canContinue, game.canContinue); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, uuid, canContinue); + } } diff --git a/src/main/java/wooteco/chess/entity/GameRepository.java b/src/main/java/wooteco/chess/entity/GameRepository.java index ae37145308..358ad35233 100644 --- a/src/main/java/wooteco/chess/entity/GameRepository.java +++ b/src/main/java/wooteco/chess/entity/GameRepository.java @@ -3,6 +3,10 @@ import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; +import java.util.List; + @Repository public interface GameRepository extends CrudRepository { + @Override + List findAll(); } diff --git a/src/test/java/wooteco/chess/entity/GameRepositoryTest.java b/src/test/java/wooteco/chess/entity/GameRepositoryTest.java index 30f2a02620..b8f618c48f 100644 --- a/src/test/java/wooteco/chess/entity/GameRepositoryTest.java +++ b/src/test/java/wooteco/chess/entity/GameRepositoryTest.java @@ -5,14 +5,16 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringExtension; -import org.springframework.transaction.annotation.Transactional; + +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) @DataJdbcTest -@Transactional +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) class GameRepositoryTest { @Autowired @@ -31,4 +33,20 @@ void save_normal_test() { assertThat(game.getUuid()).isEqualTo(uuid); assertThat(game.getCanContinue()).isEqualTo(true); } + + @DisplayName("게임 목록 조회 기능 구현") + @Test + void selectAll_test() { + String firstGameName = "first game"; + String secondGameName = "second game"; + String firstUuid = "1q2w3e4r5t6y7u8i9o0p1q2w32e4t5y5u"; + String secondUuid = "1q2w3e4r5t6y7u8i9o0p1q4ky985myktl"; + + Game firstGame = gameRepository.save(new Game(firstGameName, firstUuid, true)); + Game secondGame = gameRepository.save(new Game(secondGameName, secondUuid, true)); + + List games = gameRepository.findAll(); + + assertThat(games).contains(firstGame, secondGame); + } } \ No newline at end of file From f8faa6b2b3dc2926da942507538481d9502a8291 Mon Sep 17 00:00:00 2001 From: toneyparky Date: Wed, 29 Apr 2020 13:45:12 +0900 Subject: [PATCH 06/22] =?UTF-8?q?style:=20=EC=BB=A8=EB=B2=A4=EC=85=98?= =?UTF-8?q?=EC=9D=84=20=EC=9C=84=ED=95=9C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/schema.sql | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql index 67fca8ef3d..8099e8c9c3 100644 --- a/src/main/resources/schema.sql +++ b/src/main/resources/schema.sql @@ -1,16 +1,16 @@ -create table if NOT EXISTS game ( - id bigint not null auto_increment, - uuid varchar(36) not null, - name varchar(255) not null, - can_continue tinyint(1) not null, - primary key(id) +CREATE TABLE IF NOT EXISTS game ( + id BIGINT NOT NULL AUTO_INCREMENT, + uuid VARCHAR(36) NOT NULL, + name VARCHAR(255) NOT NULL, + can_continue BOOL NOT NULL, + PRIMARY KEY(id) ); -create table if NOT EXISTS history ( - id bigint not null auto_increment, - start varchar(2) not null, - end varchar(2) not null, - game_id bigint not null, - primary key(id), - foreign key(game_id) references game(id) +CREATE TABLE IF NOT EXISTS history ( + id BIGINT NOT NULL AUTO_INCREMENT, + start VARCHAR(2) NOT NULL, + end VARCHAR(2) NOT NULL, + game_id BIGINT NOT NULL, + PRIMARY KEY (id), + FOREIGN KEY (game_id) REFERENCES game(id) ); \ No newline at end of file From 9fd31b874afd3514a64790cee1f766421bfc183e Mon Sep 17 00:00:00 2001 From: toneyparky Date: Wed, 29 Apr 2020 15:31:33 +0900 Subject: [PATCH 07/22] =?UTF-8?q?feat:=20game=20=EC=97=85=EB=8D=B0?= =?UTF-8?q?=EC=9D=B4=ED=8A=B8=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GameRepository findByUuid() 추가 GameRepositoryTest 업데이트 테스트 작성 Game 어노테이션 컨벤션 수정 History 어노테이션 컨벤션 수정 --- src/main/java/wooteco/chess/entity/Game.java | 12 ++++----- .../wooteco/chess/entity/GameRepository.java | 5 ++++ .../java/wooteco/chess/entity/History.java | 10 +++---- .../chess/entity/GameRepositoryTest.java | 26 +++++++++++++------ 4 files changed, 32 insertions(+), 21 deletions(-) diff --git a/src/main/java/wooteco/chess/entity/Game.java b/src/main/java/wooteco/chess/entity/Game.java index b53f639aa2..b026c2fdaa 100644 --- a/src/main/java/wooteco/chess/entity/Game.java +++ b/src/main/java/wooteco/chess/entity/Game.java @@ -1,17 +1,15 @@ package wooteco.chess.entity; import org.springframework.data.annotation.Id; -import org.springframework.data.relational.core.mapping.Column; -import org.springframework.data.relational.core.mapping.Table; import java.util.Objects; -@Table("game") public class Game { - private @Id Long id; - private @Column("name") String name; - private @Column("uuid") String uuid; - private @Column("can_continue") Boolean canContinue; + @Id + private Long id; + private String name; + private String uuid; + private Boolean canContinue; public Game() { } diff --git a/src/main/java/wooteco/chess/entity/GameRepository.java b/src/main/java/wooteco/chess/entity/GameRepository.java index 358ad35233..d64e1a040d 100644 --- a/src/main/java/wooteco/chess/entity/GameRepository.java +++ b/src/main/java/wooteco/chess/entity/GameRepository.java @@ -1,6 +1,8 @@ package wooteco.chess.entity; +import org.springframework.data.jdbc.repository.query.Query; import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; @@ -9,4 +11,7 @@ public interface GameRepository extends CrudRepository { @Override List findAll(); + + @Query("SELECT * FROM game WHERE uuid = :uuid") + Game findByUuid(@Param("uuid") String uuid); } diff --git a/src/main/java/wooteco/chess/entity/History.java b/src/main/java/wooteco/chess/entity/History.java index fc56fa85be..f73ae24766 100644 --- a/src/main/java/wooteco/chess/entity/History.java +++ b/src/main/java/wooteco/chess/entity/History.java @@ -1,14 +1,12 @@ package wooteco.chess.entity; import org.springframework.data.annotation.Id; -import org.springframework.data.relational.core.mapping.Column; -import org.springframework.data.relational.core.mapping.Table; -@Table("history") public class History { - private @Id Long id; - private @Column("start") String start; - private @Column("end") String end; + @Id + private Long id; + private String start; + private String end; public History() { } diff --git a/src/test/java/wooteco/chess/entity/GameRepositoryTest.java b/src/test/java/wooteco/chess/entity/GameRepositoryTest.java index b8f618c48f..47edf67282 100644 --- a/src/test/java/wooteco/chess/entity/GameRepositoryTest.java +++ b/src/test/java/wooteco/chess/entity/GameRepositoryTest.java @@ -17,29 +17,27 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) class GameRepositoryTest { + private final String firstGameName = "first game"; + private final String firstUuid = "1q2w3e4r5t6y7u8i9o0p1q2w32e4t5y5u"; + @Autowired private GameRepository gameRepository; @DisplayName("save 새 게임 시작시 게임정보 저장 테스트") @Test void save_normal_test() { - String gameName = "first game"; - String uuid = "1q2w3e4r5t6y7u8i9o0p1q2w32e4t5y5u"; - - Game game = gameRepository.save(new Game(gameName, uuid, true)); + Game game = gameRepository.save(new Game(firstGameName, firstUuid, true)); assertThat(game.getId()).isEqualTo(1); - assertThat(game.getName()).isEqualTo(gameName); - assertThat(game.getUuid()).isEqualTo(uuid); + assertThat(game.getName()).isEqualTo(firstGameName); + assertThat(game.getUuid()).isEqualTo(firstUuid); assertThat(game.getCanContinue()).isEqualTo(true); } @DisplayName("게임 목록 조회 기능 구현") @Test void selectAll_test() { - String firstGameName = "first game"; String secondGameName = "second game"; - String firstUuid = "1q2w3e4r5t6y7u8i9o0p1q2w32e4t5y5u"; String secondUuid = "1q2w3e4r5t6y7u8i9o0p1q4ky985myktl"; Game firstGame = gameRepository.save(new Game(firstGameName, firstUuid, true)); @@ -49,4 +47,16 @@ void selectAll_test() { assertThat(games).contains(firstGame, secondGame); } + + @DisplayName("이미 저장되어있는 게임에 canContinue를 false로 변경 확인") + @Test + void save_update_can_continue_column() { + gameRepository.save(new Game(firstGameName, firstUuid, true)); + + Game foundGame = gameRepository.findByUuid(firstUuid); + + Game actualGame = gameRepository.save(new Game(foundGame.getId(), foundGame.getName(), foundGame.getUuid(), false)); + + assertThat(actualGame.getCanContinue()).isEqualTo(false); + } } \ No newline at end of file From 2435e2dac0c23fe75233ccdaa82d50e8e89edc73 Mon Sep 17 00:00:00 2001 From: toneyparky Date: Wed, 29 Apr 2020 16:10:44 +0900 Subject: [PATCH 08/22] =?UTF-8?q?feat:=20history=20=EC=B6=94=EA=B0=80=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit History GameRef와 의존 schema.sql history_game테이블 생성 HistoryRepositoryTest 테스트 코드 추가 --- .../java/wooteco/chess/entity/GameRef.java | 15 +++++++ .../java/wooteco/chess/entity/History.java | 7 +++ src/main/resources/schema.sql | 9 ++-- .../chess/entity/HistoryRepositoryTest.java | 43 +++++++++++++++++++ 4 files changed, 71 insertions(+), 3 deletions(-) create mode 100644 src/main/java/wooteco/chess/entity/GameRef.java create mode 100644 src/test/java/wooteco/chess/entity/HistoryRepositoryTest.java diff --git a/src/main/java/wooteco/chess/entity/GameRef.java b/src/main/java/wooteco/chess/entity/GameRef.java new file mode 100644 index 0000000000..70bac00caa --- /dev/null +++ b/src/main/java/wooteco/chess/entity/GameRef.java @@ -0,0 +1,15 @@ +package wooteco.chess.entity; + +import org.springframework.data.relational.core.mapping.Table; + +@Table("history_game") +public class GameRef { + private Long game; + + public GameRef() { + } + + public GameRef(Game game) { + this.game = game.getId(); + } +} diff --git a/src/main/java/wooteco/chess/entity/History.java b/src/main/java/wooteco/chess/entity/History.java index f73ae24766..98cd0eb0da 100644 --- a/src/main/java/wooteco/chess/entity/History.java +++ b/src/main/java/wooteco/chess/entity/History.java @@ -7,6 +7,7 @@ public class History { private Long id; private String start; private String end; + private GameRef game; public History() { } @@ -16,6 +17,12 @@ public History(String start, String end) { this.end = end; } + public History(String start, String end, Game game) { + this.start = start; + this.end = end; + this.game = new GameRef(game); + } + public Long getId() { return id; } diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql index 8099e8c9c3..c85172017f 100644 --- a/src/main/resources/schema.sql +++ b/src/main/resources/schema.sql @@ -10,7 +10,10 @@ CREATE TABLE IF NOT EXISTS history ( id BIGINT NOT NULL AUTO_INCREMENT, start VARCHAR(2) NOT NULL, end VARCHAR(2) NOT NULL, - game_id BIGINT NOT NULL, - PRIMARY KEY (id), - FOREIGN KEY (game_id) REFERENCES game(id) + PRIMARY KEY (id) +); + +CREATE TABLE IF NOT EXISTS history_game ( + history BIGINT NOT NULL, + game BIGINT NOT NULL ); \ No newline at end of file diff --git a/src/test/java/wooteco/chess/entity/HistoryRepositoryTest.java b/src/test/java/wooteco/chess/entity/HistoryRepositoryTest.java new file mode 100644 index 0000000000..d14d4c8ecd --- /dev/null +++ b/src/test/java/wooteco/chess/entity/HistoryRepositoryTest.java @@ -0,0 +1,43 @@ +package wooteco.chess.entity; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(SpringExtension.class) +@DataJdbcTest +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) +class HistoryRepositoryTest { + + final String firstGameName = "first game"; + final String firstUuid = "1q2w3e4r5t6y7u8i9o0p1q2w32e4t5y5u"; + + @Autowired + private HistoryRepository historyRepository; + + @Autowired + private GameRepository gameRepository; + + @DisplayName("특정 게임에 해당되는 히스토리 생성 테스트") + @Test + void save_history_from_specific_game() { + Game game = gameRepository.save(new Game(firstGameName, firstUuid, true)); + History history = new History("a2", "a4", game); + historyRepository.save(history); + + History persistHistory = historyRepository.findById(history.getId()) + .orElseThrow(RuntimeException::new); + + assertThat(persistHistory).isNotNull(); + assertThat(persistHistory.getId()).isEqualTo(1); + assertThat(persistHistory.getStart()).isEqualTo(history.getStart()); + assertThat(persistHistory.getEnd()).isEqualTo(history.getEnd()); + } + +} \ No newline at end of file From 050afe4ca3da55dee4d66aec1f7201ecb0e41f3a Mon Sep 17 00:00:00 2001 From: toneyparky Date: Wed, 29 Apr 2020 16:44:59 +0900 Subject: [PATCH 09/22] =?UTF-8?q?feat:=20Game=EC=97=90=20=ED=95=B4?= =?UTF-8?q?=EB=8B=B9=ED=95=98=EB=8A=94=20=ED=9E=88=EC=8A=A4=ED=86=A0?= =?UTF-8?q?=EB=A6=AC=20=EC=A0=84=EC=B2=B4=20=EC=A1=B0=ED=9A=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Game histories 추가 schema.sql history_game 테이블 삭제 GameRepositoryTest 게임에 해당하는 전체 히스토리 조회 테스트 추가 --- src/main/java/wooteco/chess/entity/Game.java | 11 +++++ .../java/wooteco/chess/entity/GameRef.java | 15 ------- .../java/wooteco/chess/entity/History.java | 7 --- src/main/resources/schema.sql | 9 ++-- .../chess/entity/GameRepositoryTest.java | 23 ++++++++++ .../chess/entity/HistoryRepositoryTest.java | 43 ------------------- 6 files changed, 37 insertions(+), 71 deletions(-) delete mode 100644 src/main/java/wooteco/chess/entity/GameRef.java delete mode 100644 src/test/java/wooteco/chess/entity/HistoryRepositoryTest.java diff --git a/src/main/java/wooteco/chess/entity/Game.java b/src/main/java/wooteco/chess/entity/Game.java index b026c2fdaa..2d780985e1 100644 --- a/src/main/java/wooteco/chess/entity/Game.java +++ b/src/main/java/wooteco/chess/entity/Game.java @@ -2,7 +2,9 @@ import org.springframework.data.annotation.Id; +import java.util.HashSet; import java.util.Objects; +import java.util.Set; public class Game { @Id @@ -10,6 +12,7 @@ public class Game { private String name; private String uuid; private Boolean canContinue; + private Set histories = new HashSet<>(); public Game() { } @@ -32,6 +35,10 @@ public Game(String gameName, String uuid, Boolean canContinue) { this.canContinue = canContinue; } + public void addHistory(History history) { + histories.add(history); + } + public Long getId() { return id; } @@ -48,6 +55,10 @@ public Boolean getCanContinue() { return canContinue; } + public Set getHistories() { + return histories; + } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/src/main/java/wooteco/chess/entity/GameRef.java b/src/main/java/wooteco/chess/entity/GameRef.java deleted file mode 100644 index 70bac00caa..0000000000 --- a/src/main/java/wooteco/chess/entity/GameRef.java +++ /dev/null @@ -1,15 +0,0 @@ -package wooteco.chess.entity; - -import org.springframework.data.relational.core.mapping.Table; - -@Table("history_game") -public class GameRef { - private Long game; - - public GameRef() { - } - - public GameRef(Game game) { - this.game = game.getId(); - } -} diff --git a/src/main/java/wooteco/chess/entity/History.java b/src/main/java/wooteco/chess/entity/History.java index 98cd0eb0da..f73ae24766 100644 --- a/src/main/java/wooteco/chess/entity/History.java +++ b/src/main/java/wooteco/chess/entity/History.java @@ -7,7 +7,6 @@ public class History { private Long id; private String start; private String end; - private GameRef game; public History() { } @@ -17,12 +16,6 @@ public History(String start, String end) { this.end = end; } - public History(String start, String end, Game game) { - this.start = start; - this.end = end; - this.game = new GameRef(game); - } - public Long getId() { return id; } diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql index c85172017f..36dbe9ac78 100644 --- a/src/main/resources/schema.sql +++ b/src/main/resources/schema.sql @@ -10,10 +10,7 @@ CREATE TABLE IF NOT EXISTS history ( id BIGINT NOT NULL AUTO_INCREMENT, start VARCHAR(2) NOT NULL, end VARCHAR(2) NOT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE IF NOT EXISTS history_game ( - history BIGINT NOT NULL, - game BIGINT NOT NULL + game BIGINT NOT NULL, + PRIMARY KEY (id), + FOREIGN KEY(game) REFERENCES game(id) ); \ No newline at end of file diff --git a/src/test/java/wooteco/chess/entity/GameRepositoryTest.java b/src/test/java/wooteco/chess/entity/GameRepositoryTest.java index 47edf67282..1c90bc69aa 100644 --- a/src/test/java/wooteco/chess/entity/GameRepositoryTest.java +++ b/src/test/java/wooteco/chess/entity/GameRepositoryTest.java @@ -9,6 +9,7 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List; +import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; @@ -59,4 +60,26 @@ void save_update_can_continue_column() { assertThat(actualGame.getCanContinue()).isEqualTo(false); } + + @DisplayName("게임 선택 시 해당하는 히스토리 조회") + @Test + void getHistories_history_from_specific_game() { + Game firstGame = gameRepository.save(new Game(firstGameName, firstUuid, true)); + Game secondGame = gameRepository.save(new Game("secondGameName", "secondUuid", true)); + History firstHistory = new History("a2", "a4"); + History secondHistory = new History("b2", "b4"); + History thirdHistory = new History("a7", "a5"); + firstGame.addHistory(firstHistory); + secondGame.addHistory(secondHistory); + firstGame.addHistory(thirdHistory); + + Game persistFirstGame = gameRepository.save(firstGame); + Game persistSecondGame = gameRepository.save(secondGame); + + Set firstHistories = persistFirstGame.getHistories(); + Set secondHistories = persistSecondGame.getHistories(); + + assertThat(firstHistories).contains(firstHistory, thirdHistory); + assertThat(secondHistories).contains(secondHistory); + } } \ No newline at end of file diff --git a/src/test/java/wooteco/chess/entity/HistoryRepositoryTest.java b/src/test/java/wooteco/chess/entity/HistoryRepositoryTest.java deleted file mode 100644 index d14d4c8ecd..0000000000 --- a/src/test/java/wooteco/chess/entity/HistoryRepositoryTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package wooteco.chess.entity; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; - -@ExtendWith(SpringExtension.class) -@DataJdbcTest -@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) -class HistoryRepositoryTest { - - final String firstGameName = "first game"; - final String firstUuid = "1q2w3e4r5t6y7u8i9o0p1q2w32e4t5y5u"; - - @Autowired - private HistoryRepository historyRepository; - - @Autowired - private GameRepository gameRepository; - - @DisplayName("특정 게임에 해당되는 히스토리 생성 테스트") - @Test - void save_history_from_specific_game() { - Game game = gameRepository.save(new Game(firstGameName, firstUuid, true)); - History history = new History("a2", "a4", game); - historyRepository.save(history); - - History persistHistory = historyRepository.findById(history.getId()) - .orElseThrow(RuntimeException::new); - - assertThat(persistHistory).isNotNull(); - assertThat(persistHistory.getId()).isEqualTo(1); - assertThat(persistHistory.getStart()).isEqualTo(history.getStart()); - assertThat(persistHistory.getEnd()).isEqualTo(history.getEnd()); - } - -} \ No newline at end of file From 66f72e8c10bf46c328e5635916f3c739bd436a2f Mon Sep 17 00:00:00 2001 From: toneyparky Date: Wed, 29 Apr 2020 16:51:34 +0900 Subject: [PATCH 10/22] =?UTF-8?q?fix:=20=EC=A2=85=EB=A3=8C=EB=90=9C=20?= =?UTF-8?q?=EA=B2=8C=EC=9E=84=EC=9D=80=20=EC=A0=84=EC=B2=B4=20=EC=A1=B0?= =?UTF-8?q?=ED=9A=8C=20=EB=AA=A9=EB=A1=9D=EC=97=90=EC=84=9C=20=EC=A0=9C?= =?UTF-8?q?=EC=99=B8=ED=95=98=EB=8F=84=EB=A1=9D=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GameRepository findAll에 쿼리문 추가 --- src/main/java/wooteco/chess/entity/GameRepository.java | 1 + .../java/wooteco/chess/entity/GameRepositoryTest.java | 9 ++++----- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/wooteco/chess/entity/GameRepository.java b/src/main/java/wooteco/chess/entity/GameRepository.java index d64e1a040d..ede182dbd4 100644 --- a/src/main/java/wooteco/chess/entity/GameRepository.java +++ b/src/main/java/wooteco/chess/entity/GameRepository.java @@ -10,6 +10,7 @@ @Repository public interface GameRepository extends CrudRepository { @Override + @Query("SELECT * FROM game WHERE can_continue = true") List findAll(); @Query("SELECT * FROM game WHERE uuid = :uuid") diff --git a/src/test/java/wooteco/chess/entity/GameRepositoryTest.java b/src/test/java/wooteco/chess/entity/GameRepositoryTest.java index 1c90bc69aa..f64c06e21b 100644 --- a/src/test/java/wooteco/chess/entity/GameRepositoryTest.java +++ b/src/test/java/wooteco/chess/entity/GameRepositoryTest.java @@ -35,18 +35,17 @@ void save_normal_test() { assertThat(game.getCanContinue()).isEqualTo(true); } - @DisplayName("게임 목록 조회 기능 구현") + @DisplayName("게임 목록 중 진행중인 게임 조회 기능 구현") @Test void selectAll_test() { - String secondGameName = "second game"; - String secondUuid = "1q2w3e4r5t6y7u8i9o0p1q4ky985myktl"; - Game firstGame = gameRepository.save(new Game(firstGameName, firstUuid, true)); - Game secondGame = gameRepository.save(new Game(secondGameName, secondUuid, true)); + Game secondGame = gameRepository.save(new Game("secondGameName", "secondUuid", true)); + Game thirdGame = gameRepository.save(new Game("thirdGameName", "thirdUuid", false)); List games = gameRepository.findAll(); assertThat(games).contains(firstGame, secondGame); + assertThat(games).doesNotContain(thirdGame); } @DisplayName("이미 저장되어있는 게임에 canContinue를 false로 변경 확인") From e81e5136ea83d45498a3543143f88ea2aa9377c2 Mon Sep 17 00:00:00 2001 From: toneyparky Date: Fri, 1 May 2020 17:45:37 +0900 Subject: [PATCH 11/22] =?UTF-8?q?feat:=20=EA=B2=8C=EC=9E=84=EC=9D=84=20?= =?UTF-8?q?=EC=83=9D=EC=84=B1=ED=95=98=EA=B3=A0=20=ED=95=B4=EB=8B=B9=20?= =?UTF-8?q?=EA=B2=8C=EC=9E=84=EC=9D=84=20=EB=B6=88=EB=9F=AC=EC=98=A4?= =?UTF-8?q?=EB=8A=94=20=EA=B8=B0=EB=8A=A5=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SpringChessController /new로 post 요청을 보내는 라우트 추가 SpringDataJDBCChessService createGameBy로 메서드명 수정 --- .../controller/SpringChessController.java | 34 +++++++++++---- .../java/wooteco/chess/dto/ChessGameDto.java | 14 ++++++ src/main/java/wooteco/chess/entity/Game.java | 19 ++------ .../wooteco/chess/entity/GameRepository.java | 3 -- .../service/SpringDataJDBCChessService.java | 43 +++++++++++++++++++ src/main/resources/schema.sql | 1 - src/main/resources/static/public/js/chess.js | 10 +++-- src/main/resources/static/public/js/index.js | 20 +++++++++ src/main/resources/templates/chess.hbs | 4 +- src/main/resources/templates/index.hbs | 3 +- .../chess/entity/GameRepositoryTest.java | 20 ++++----- 11 files changed, 125 insertions(+), 46 deletions(-) create mode 100644 src/main/resources/static/public/js/index.js diff --git a/src/main/java/wooteco/chess/controller/SpringChessController.java b/src/main/java/wooteco/chess/controller/SpringChessController.java index 6f96a4716f..90368fb024 100644 --- a/src/main/java/wooteco/chess/controller/SpringChessController.java +++ b/src/main/java/wooteco/chess/controller/SpringChessController.java @@ -19,7 +19,7 @@ @Controller public class SpringChessController { @Autowired - private SpringDataJDBCChessService springChessService; + private SpringDataJDBCChessService springDataJDBCChessService; @GetMapping("/") public ModelAndView routeMainPage() { @@ -29,19 +29,35 @@ public ModelAndView routeMainPage() { return modelAndView; } - @GetMapping("/new") - public ModelAndView startNewGame() throws SQLException { + @PostMapping("/new") + @ResponseBody + public String saveNewGame(@RequestBody Map param) { + System.out.println(param.get("gameName")); + ChessGameDto chessGameDto = springDataJDBCChessService.createGameBy((String) param.get("gameName")); + + return JsonTransformer.toJson(chessGameDto); + } + + @GetMapping("/game/{id}") + @ResponseBody + public ModelAndView startGame(@PathVariable Long id) { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("chess"); modelAndView.addObject("normalStatus", NormalStatus.YES.isNormalStatus()); - springChessService.clearHistory(); return modelAndView; } + @GetMapping("/board/{id}") + @ResponseBody + public String setBoard(@PathVariable Long id) { + ChessGameDto chessGameDto = springDataJDBCChessService.setBoardBy(id); + return JsonTransformer.toJson(chessGameDto); + } + @GetMapping("/board") @ResponseBody public String setBoard() throws SQLException { - ChessGameDto chessGameDto = springChessService.setBoard(); + ChessGameDto chessGameDto = springDataJDBCChessService.setBoard(); return JsonTransformer.toJson(chessGameDto); } @@ -50,7 +66,7 @@ public String setBoard() throws SQLException { public String getMovablePositions(@RequestParam String source) throws SQLException { Map model = new HashMap<>(); try { - MovablePositionsDto movablePositionsDto = springChessService.findMovablePositions(source); + MovablePositionsDto movablePositionsDto = springDataJDBCChessService.findMovablePositions(source); model.put("movable", movablePositionsDto.getMovablePositionNames()); model.put("position", movablePositionsDto.getPosition()); model.put("normalStatus", NormalStatus.YES.isNormalStatus()); @@ -66,7 +82,7 @@ public String getMovablePositions(@RequestParam String source) throws SQLExcepti @ResponseBody public String checkMovable(@RequestParam String startPosition, @RequestParam String destination) { Map model = new HashMap<>(); - MoveStatusDto moveStatusDto = springChessService.checkMovable( + MoveStatusDto moveStatusDto = springDataJDBCChessService.checkMovable( new MovingPosition(startPosition, destination)); model.put("normalStatus", moveStatusDto.getNormalStatus()); @@ -78,14 +94,14 @@ public String checkMovable(@RequestParam String startPosition, @RequestParam Str public ModelAndView saveHistory(@RequestBody MovingPosition movingPosition) throws SQLException { ModelAndView modelAndView = new ModelAndView(); - MoveStatusDto moveStatusDto = springChessService.move(movingPosition); + MoveStatusDto moveStatusDto = springDataJDBCChessService.move(movingPosition); if (moveStatusDto.getWinner().isNone()) { modelAndView.setViewName("chess"); return modelAndView; } modelAndView.setViewName("result"); modelAndView.addObject("winner", moveStatusDto.getWinner()); - springChessService.clearHistory(); + springDataJDBCChessService.clearHistory(); return modelAndView; } diff --git a/src/main/java/wooteco/chess/dto/ChessGameDto.java b/src/main/java/wooteco/chess/dto/ChessGameDto.java index 9fb3f033ae..1cd65b4b68 100644 --- a/src/main/java/wooteco/chess/dto/ChessGameDto.java +++ b/src/main/java/wooteco/chess/dto/ChessGameDto.java @@ -4,6 +4,7 @@ import wooteco.chess.domain.game.Turn; public class ChessGameDto { + private Long gameId; private BoardDto boardDto; private Turn turn; private ScoreResult score; @@ -14,6 +15,19 @@ public ChessGameDto(BoardDto boardDto, Turn turn, ScoreResult score, boolean nor this.turn = turn; this.score = score; this.normalStatus = normalStatus; + this.gameId = null; // TODO: 2020/04/29 제거할 방법 생각 + } + + public ChessGameDto(Long gameId, BoardDto boardDto, Turn turn, ScoreResult score, boolean normalStatus) { + this.gameId = gameId; + this.boardDto = boardDto; + this.turn = turn; + this.score = score; + this.normalStatus = normalStatus; + } + + public Long getGameId() { + return gameId; } public BoardDto getBoardDto() { diff --git a/src/main/java/wooteco/chess/entity/Game.java b/src/main/java/wooteco/chess/entity/Game.java index 2d780985e1..8399700e61 100644 --- a/src/main/java/wooteco/chess/entity/Game.java +++ b/src/main/java/wooteco/chess/entity/Game.java @@ -10,28 +10,20 @@ public class Game { @Id private Long id; private String name; - private String uuid; private Boolean canContinue; private Set histories = new HashSet<>(); public Game() { } - public Game(String name, String uuid) { - this.name = name; - this.uuid = uuid; - } - - public Game(Long id, String name, String uuid, Boolean canContinue) { + public Game(Long id, String name, Boolean canContinue) { this.id = id; this.name = name; - this.uuid = uuid; this.canContinue = canContinue; } - public Game(String gameName, String uuid, Boolean canContinue) { + public Game(String gameName, Boolean canContinue) { this.name = gameName; - this.uuid = uuid; this.canContinue = canContinue; } @@ -47,10 +39,6 @@ public String getName() { return name; } - public String getUuid() { - return uuid; - } - public Boolean getCanContinue() { return canContinue; } @@ -70,12 +58,11 @@ public boolean equals(Object o) { Game game = (Game) o; return Objects.equals(id, game.id) && Objects.equals(name, game.name) && - Objects.equals(uuid, game.uuid) && Objects.equals(canContinue, game.canContinue); } @Override public int hashCode() { - return Objects.hash(id, name, uuid, canContinue); + return Objects.hash(id, name, canContinue); } } diff --git a/src/main/java/wooteco/chess/entity/GameRepository.java b/src/main/java/wooteco/chess/entity/GameRepository.java index ede182dbd4..7436384b1e 100644 --- a/src/main/java/wooteco/chess/entity/GameRepository.java +++ b/src/main/java/wooteco/chess/entity/GameRepository.java @@ -12,7 +12,4 @@ public interface GameRepository extends CrudRepository { @Override @Query("SELECT * FROM game WHERE can_continue = true") List findAll(); - - @Query("SELECT * FROM game WHERE uuid = :uuid") - Game findByUuid(@Param("uuid") String uuid); } diff --git a/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java b/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java index acc201e345..94fdaf80b6 100644 --- a/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java +++ b/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java @@ -9,11 +9,15 @@ import wooteco.chess.dto.ChessGameDto; import wooteco.chess.dto.MovablePositionsDto; import wooteco.chess.dto.MoveStatusDto; +import wooteco.chess.entity.Game; +import wooteco.chess.entity.GameRepository; import wooteco.chess.entity.History; import wooteco.chess.entity.HistoryRepository; import java.util.Collections; import java.util.List; +import java.util.Set; +import java.util.UUID; import java.util.stream.Collectors; @Service @@ -21,6 +25,9 @@ public class SpringDataJDBCChessService { @Autowired private HistoryRepository historyRepository; + @Autowired + private GameRepository gameRepository; + public void clearHistory() { historyRepository.deleteAll(); } @@ -33,6 +40,42 @@ public ChessGameDto setBoard() { return new ChessGameDto(new BoardDto(chessGame.getPieces()), chessGame.getTurn(), chessGame.calculateScore(), NormalStatus.YES.isNormalStatus()); } + public ChessGameDto createGameBy(String gameName) { + ChessGame chessGame = new ChessGame(); + Long gameId = save(gameName); + return new ChessGameDto(gameId, new BoardDto(chessGame.getPieces()), chessGame.getTurn(), + chessGame.calculateScore(), NormalStatus.YES.isNormalStatus()); + } + + private Long save(String gameName) { + Game game = gameRepository.save(new Game(gameName, true)); + return game.getId(); + } + + public ChessGameDto setBoardBy(Long id) { + ChessGame chessGame = new ChessGame(); + load(chessGame, id); + return new ChessGameDto(new BoardDto(chessGame.getPieces()), chessGame.getTurn(), + chessGame.calculateScore(), NormalStatus.YES.isNormalStatus()); + } + + private void load(ChessGame chessGame, Long id) { + List histories = selectAllHistoryBy(id); + for (MovingPosition movingPosition : histories) { + chessGame.move(movingPosition); + } + } + + private List selectAllHistoryBy(Long id) { + Game game = gameRepository.findById(id).orElseThrow(() -> + new IllegalArgumentException("없는 게임 id 입니다.")); + Set histories = game.getHistories(); + + return Collections.unmodifiableList(histories.stream() + .map(h -> new MovingPosition(h.getStart(), h.getEnd())) + .collect(Collectors.toList())); + } + private void load(ChessGame chessGame) { List histories = selectAllHistory(); diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql index 36dbe9ac78..54ab188ce3 100644 --- a/src/main/resources/schema.sql +++ b/src/main/resources/schema.sql @@ -1,6 +1,5 @@ CREATE TABLE IF NOT EXISTS game ( id BIGINT NOT NULL AUTO_INCREMENT, - uuid VARCHAR(36) NOT NULL, name VARCHAR(255) NOT NULL, can_continue BOOL NOT NULL, PRIMARY KEY(id) diff --git a/src/main/resources/static/public/js/chess.js b/src/main/resources/static/public/js/chess.js index 3c0e7cf774..7223c073e5 100644 --- a/src/main/resources/static/public/js/chess.js +++ b/src/main/resources/static/public/js/chess.js @@ -16,7 +16,8 @@ window.onload = function () { let startPosition = null; async function getChessGame() { - const response = await fetch("http://localhost:8080/board"); + let pathName = window.location.pathname; + const response = await fetch(`http://localhost:8080/board/${pathName.substring(6)}`); return await response.json(); } @@ -50,8 +51,10 @@ window.onload = function () { } (async function () { + console.log("start!"); const chessGame = await getChessGame(); - const board = chessGame["boardDto"]["board"]; + const board = await chessGame["boardDto"]["board"]; + console.log(board); const turn = chessGame["turn"]; const score = chessGame["score"]["scores"]; @@ -65,7 +68,8 @@ window.onload = function () { })(); function chooseFirstPosition(position) { - fetch(`http://localhost:8080/source?source=${position}`, {method: "GET"}) + fetch(`http://localhost:8080/source?source=${position}`, + {method: "GET"}) .then(res => res.json()) .then(data => { startPosition = data.position; diff --git a/src/main/resources/static/public/js/index.js b/src/main/resources/static/public/js/index.js new file mode 100644 index 0000000000..1c792abb75 --- /dev/null +++ b/src/main/resources/static/public/js/index.js @@ -0,0 +1,20 @@ +window.onload = function () { + document.querySelector("#new").addEventListener("click", () => { + let gameName = prompt("게임 이름을 입력하세요."); + fetch("http://localhost:8080/new", { + method: "POST", + body: JSON.stringify({ + gameName: gameName + }), + headers: {"Content-Type": "application/json"} + }) + .then(async function(response) { + return await response.json(); + }) + .then(data => { + console.log(data); + let gameId = data["gameId"]; + window.location.href = `/game/${gameId}`; + }); + }); +}; \ No newline at end of file diff --git a/src/main/resources/templates/chess.hbs b/src/main/resources/templates/chess.hbs index 11b7a9abb7..e9643f7998 100644 --- a/src/main/resources/templates/chess.hbs +++ b/src/main/resources/templates/chess.hbs @@ -3,7 +3,7 @@ ♛Play Chess Game♚ - +
@@ -100,6 +100,6 @@
- + \ No newline at end of file diff --git a/src/main/resources/templates/index.hbs b/src/main/resources/templates/index.hbs index f804b32259..976d1b5d0c 100644 --- a/src/main/resources/templates/index.hbs +++ b/src/main/resources/templates/index.hbs @@ -8,11 +8,12 @@

체스게임

- +
+ \ No newline at end of file diff --git a/src/test/java/wooteco/chess/entity/GameRepositoryTest.java b/src/test/java/wooteco/chess/entity/GameRepositoryTest.java index f64c06e21b..ea325e91a1 100644 --- a/src/test/java/wooteco/chess/entity/GameRepositoryTest.java +++ b/src/test/java/wooteco/chess/entity/GameRepositoryTest.java @@ -19,7 +19,6 @@ class GameRepositoryTest { private final String firstGameName = "first game"; - private final String firstUuid = "1q2w3e4r5t6y7u8i9o0p1q2w32e4t5y5u"; @Autowired private GameRepository gameRepository; @@ -27,20 +26,19 @@ class GameRepositoryTest { @DisplayName("save 새 게임 시작시 게임정보 저장 테스트") @Test void save_normal_test() { - Game game = gameRepository.save(new Game(firstGameName, firstUuid, true)); + Game game = gameRepository.save(new Game(firstGameName, true)); assertThat(game.getId()).isEqualTo(1); assertThat(game.getName()).isEqualTo(firstGameName); - assertThat(game.getUuid()).isEqualTo(firstUuid); assertThat(game.getCanContinue()).isEqualTo(true); } @DisplayName("게임 목록 중 진행중인 게임 조회 기능 구현") @Test void selectAll_test() { - Game firstGame = gameRepository.save(new Game(firstGameName, firstUuid, true)); - Game secondGame = gameRepository.save(new Game("secondGameName", "secondUuid", true)); - Game thirdGame = gameRepository.save(new Game("thirdGameName", "thirdUuid", false)); + Game firstGame = gameRepository.save(new Game(firstGameName, true)); + Game secondGame = gameRepository.save(new Game("secondGameName", true)); + Game thirdGame = gameRepository.save(new Game("thirdGameName", false)); List games = gameRepository.findAll(); @@ -51,11 +49,11 @@ void selectAll_test() { @DisplayName("이미 저장되어있는 게임에 canContinue를 false로 변경 확인") @Test void save_update_can_continue_column() { - gameRepository.save(new Game(firstGameName, firstUuid, true)); + gameRepository.save(new Game(firstGameName, true)); - Game foundGame = gameRepository.findByUuid(firstUuid); + Game foundGame = gameRepository.findById(1L).get(); - Game actualGame = gameRepository.save(new Game(foundGame.getId(), foundGame.getName(), foundGame.getUuid(), false)); + Game actualGame = gameRepository.save(new Game(foundGame.getId(), foundGame.getName(), false)); assertThat(actualGame.getCanContinue()).isEqualTo(false); } @@ -63,8 +61,8 @@ void save_update_can_continue_column() { @DisplayName("게임 선택 시 해당하는 히스토리 조회") @Test void getHistories_history_from_specific_game() { - Game firstGame = gameRepository.save(new Game(firstGameName, firstUuid, true)); - Game secondGame = gameRepository.save(new Game("secondGameName", "secondUuid", true)); + Game firstGame = gameRepository.save(new Game(firstGameName, true)); + Game secondGame = gameRepository.save(new Game("secondGameName", true)); History firstHistory = new History("a2", "a4"); History secondHistory = new History("b2", "b4"); History thirdHistory = new History("a7", "a5"); From 7f2ad79ea9dbe476de5decfbadb2cea5eb2d6547 Mon Sep 17 00:00:00 2001 From: toneyparky Date: Fri, 1 May 2020 19:51:48 +0900 Subject: [PATCH 12/22] =?UTF-8?q?style:=20javascript=20=EC=BB=A8=EB=B2=A4?= =?UTF-8?q?=EC=85=98=EC=9D=84=20=EC=A7=80=ED=82=A4=EA=B8=B0=20=EC=9C=84?= =?UTF-8?q?=ED=95=B4=204=EC=B9=B8=EC=97=90=EC=84=9C=202=EC=B9=B8=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=ED=83=AD=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/static/public/js/chess.js | 242 ++++++++--------- src/main/resources/static/public/js/index.js | 2 +- .../resources/templates/public/js/chess.js | 244 +++++++++--------- 3 files changed, 244 insertions(+), 244 deletions(-) diff --git a/src/main/resources/static/public/js/chess.js b/src/main/resources/static/public/js/chess.js index 7223c073e5..74316a8ff7 100644 --- a/src/main/resources/static/public/js/chess.js +++ b/src/main/resources/static/public/js/chess.js @@ -1,135 +1,135 @@ window.onload = function () { - const PIECES = { - BLACK_KING: ``, - BLACK_QUEEN: ``, - BLACK_ROOK: ``, - BLACK_BISHOP: ``, - BLACK_KNIGHT: ``, - BLACK_BLACK_PAWN: ``, - WHITE_KING: ``, - WHITE_QUEEN: ``, - WHITE_ROOK: ``, - WHITE_BISHOP: ``, - WHITE_KNIGHT: ``, - WHITE_WHITE_PAWN: ``, - }; - let startPosition = null; + const PIECES = { + BLACK_KING: ``, + BLACK_QUEEN: ``, + BLACK_ROOK: ``, + BLACK_BISHOP: ``, + BLACK_KNIGHT: ``, + BLACK_BLACK_PAWN: ``, + WHITE_KING: ``, + WHITE_QUEEN: ``, + WHITE_ROOK: ``, + WHITE_BISHOP: ``, + WHITE_KNIGHT: ``, + WHITE_WHITE_PAWN: ``, + }; + let startPosition = null; - async function getChessGame() { - let pathName = window.location.pathname; - const response = await fetch(`http://localhost:8080/board/${pathName.substring(6)}`); - return await response.json(); - } + async function getChessGame() { + let pathName = window.location.pathname; + const response = await fetch(`http://localhost:8080/board/${pathName.substring(6)}`); + return await response.json(); + } - function setBoard(board) { - document.querySelectorAll(".position").forEach(element => { - while (element.lastElementChild) { - element.removeChild(element.lastElementChild); - } - }); - Object.keys(board) - .filter(position => board[position]["pieceType"] !== "BLANK") - .forEach(position => { - const color = board[position]["color"]; - const pieceType = board[position]["pieceType"]; - document.getElementById(position) - .insertAdjacentHTML("beforeend", PIECES[`${color}_${pieceType}`]); - }); - } + function setBoard(board) { + document.querySelectorAll(".position").forEach(element => { + while (element.lastElementChild) { + element.removeChild(element.lastElementChild); + } + }); + Object.keys(board) + .filter(position => board[position]["pieceType"] !== "BLANK") + .forEach(position => { + const color = board[position]["color"]; + const pieceType = board[position]["pieceType"]; + document.getElementById(position) + .insertAdjacentHTML("beforeend", PIECES[`${color}_${pieceType}`]); + }); + } - function setTurn(turn) { - document.getElementById("turn_box") - .innerHTML = '

' + turn["color"] + "의 턴입니다." + '

'; - } + function setTurn(turn) { + document.getElementById("turn_box") + .innerHTML = '

' + turn["color"] + "의 턴입니다." + '

'; + } - function setScore(score) { - document.getElementById("score") - .innerHTML = '

' + - "WHITE 팀의 점수는 " + score["WHITE"] + "점 입니다.\n" + - "BLACK 팀의 점수는 " + score["BLACK"] + "점 입니다." + - '

'; - } + function setScore(score) { + document.getElementById("score") + .innerHTML = '

' + + "WHITE 팀의 점수는 " + score["WHITE"] + "점 입니다.\n" + + "BLACK 팀의 점수는 " + score["BLACK"] + "점 입니다." + + '

'; + } - (async function () { - console.log("start!"); - const chessGame = await getChessGame(); - const board = await chessGame["boardDto"]["board"]; - console.log(board); - const turn = chessGame["turn"]; - const score = chessGame["score"]["scores"]; + (async function () { + console.log("start!"); + const chessGame = await getChessGame(); + const board = await chessGame["boardDto"]["board"]; + console.log(board); + const turn = chessGame["turn"]; + const score = chessGame["score"]["scores"]; - if (chessGame["normalStatus"] === false) { - alert("잘못된 명령입니다."); - return; - } - setBoard(board); - setTurn(turn); - setScore(score); - })(); + if (chessGame["normalStatus"] === false) { + alert("잘못된 명령입니다."); + return; + } + setBoard(board); + setTurn(turn); + setScore(score); + })(); - function chooseFirstPosition(position) { - fetch(`http://localhost:8080/source?source=${position}`, - {method: "GET"}) - .then(res => res.json()) - .then(data => { - startPosition = data.position; - console.log(data.normalStatus); - if (data.normalStatus === false) { - alert(data.exception); - startPosition = null; - return; - } - const positions = data.movable; - positions.forEach(position => { - document.getElementById(position) - .style - .backgroundColor = "rgba(255, 100, 0, 0.2)"; - }); + function chooseFirstPosition(position) { + fetch(`http://localhost:8080/source?source=${position}`, + {method: "GET"}) + .then(res => res.json()) + .then(data => { + startPosition = data.position; + console.log(data.normalStatus); + if (data.normalStatus === false) { + alert(data.exception); + startPosition = null; + return; + } + const positions = data.movable; + positions.forEach(position => { + document.getElementById(position) + .style + .backgroundColor = "rgba(255, 100, 0, 0.2)"; + }); - document.getElementById(position) - .style - .backgroundColor = "rgba(255, 200, 0, 0.2)"; - }); - } + document.getElementById(position) + .style + .backgroundColor = "rgba(255, 200, 0, 0.2)"; + }); + } - function chooseSecondPosition(position) { - fetch(`http://localhost:8080/destination?destination=${position}&startPosition=${startPosition}`, - {method: "GET"}) - .then(res => res.json()) - .then(async data => { - if (data.normalStatus === false) { - alert(data.exception); - startPosition = null; - window.location.href = "/loading"; - return; - } - const source = startPosition; - const destination = position; - startPosition = null; + function chooseSecondPosition(position) { + fetch(`http://localhost:8080/destination?destination=${position}&startPosition=${startPosition}`, + {method: "GET"}) + .then(res => res.json()) + .then(async data => { + if (data.normalStatus === false) { + alert(data.exception); + startPosition = null; + window.location.href = "/loading"; + return; + } + const source = startPosition; + const destination = position; + startPosition = null; - await fetch("http://localhost:8080/board", { - method: "POST", - body: JSON.stringify({ - start: source, - end: destination - }), - headers: {"Content-Type": "application/json"} - }) - .then(window.location.href = "/loading"); - }); - } + await fetch("http://localhost:8080/board", { + method: "POST", + body: JSON.stringify({ + start: source, + end: destination + }), + headers: {"Content-Type": "application/json"} + }) + .then(window.location.href = "/loading"); + }); + } - document.querySelectorAll(".position").forEach( - element => { - element.addEventListener("click", (e) => { - let position = e.currentTarget.id; - e.preventDefault(); - if (startPosition == null) { - chooseFirstPosition(position); - } else { - chooseSecondPosition(position); - } - }); + document.querySelectorAll(".position").forEach( + element => { + element.addEventListener("click", (e) => { + let position = e.currentTarget.id; + e.preventDefault(); + if (startPosition == null) { + chooseFirstPosition(position); + } else { + chooseSecondPosition(position); } - ); + }); + } + ); }; \ No newline at end of file diff --git a/src/main/resources/static/public/js/index.js b/src/main/resources/static/public/js/index.js index 1c792abb75..f3927168f2 100644 --- a/src/main/resources/static/public/js/index.js +++ b/src/main/resources/static/public/js/index.js @@ -8,7 +8,7 @@ window.onload = function () { }), headers: {"Content-Type": "application/json"} }) - .then(async function(response) { + .then(async function (response) { return await response.json(); }) .then(data => { diff --git a/src/main/resources/templates/public/js/chess.js b/src/main/resources/templates/public/js/chess.js index 384e3dbe7e..cfc9cf7ba3 100644 --- a/src/main/resources/templates/public/js/chess.js +++ b/src/main/resources/templates/public/js/chess.js @@ -1,139 +1,139 @@ window.onload = function () { - const PIECES = { - BLACK_KING: ``, - BLACK_QUEEN: ``, - BLACK_ROOK: ``, - BLACK_BISHOP: ``, - BLACK_KNIGHT: ``, - BLACK_BLACK_PAWN: ``, - WHITE_KING: ``, - WHITE_QUEEN: ``, - WHITE_ROOK: ``, - WHITE_BISHOP: ``, - WHITE_KNIGHT: ``, - WHITE_WHITE_PAWN: ``, - }; - let startPosition = null; + const PIECES = { + BLACK_KING: ``, + BLACK_QUEEN: ``, + BLACK_ROOK: ``, + BLACK_BISHOP: ``, + BLACK_KNIGHT: ``, + BLACK_BLACK_PAWN: ``, + WHITE_KING: ``, + WHITE_QUEEN: ``, + WHITE_ROOK: ``, + WHITE_BISHOP: ``, + WHITE_KNIGHT: ``, + WHITE_WHITE_PAWN: ``, + }; + let startPosition = null; - async function getChessGame() { - const response = await fetch("http://localhost:4567/board"); - return await response.json(); - } - - function setBoard(board) { - document.querySelectorAll(".position").forEach(element => { - while (element.lastElementChild) { - element.removeChild(element.lastElementChild); - } - }); - Object.keys(board) - .filter(position => board[position]["pieceType"] !== "BLANK") - .forEach(position => { - const color = board[position]["color"]; - const pieceType = board[position]["pieceType"]; - document.getElementById(position) - .insertAdjacentHTML("beforeend", PIECES[`${color}_${pieceType}`]); - }); - } + async function getChessGame() { + const response = await fetch("http://localhost:4567/board"); + return await response.json(); + } - function setTurn(turn) { - document.getElementById("turn_box") - .innerHTML = '

' + turn["color"] + "의 턴입니다." + '

'; - } - - function setScore(score) { - document.getElementById("score") - .innerHTML = '

' + - "WHITE 팀의 점수는 " + score["WHITE"] + "점 입니다.\n" + - "BLACK 팀의 점수는 " + score["BLACK"] + "점 입니다." + - '

'; - } + function setBoard(board) { + document.querySelectorAll(".position").forEach(element => { + while (element.lastElementChild) { + element.removeChild(element.lastElementChild); + } + }); + Object.keys(board) + .filter(position => board[position]["pieceType"] !== "BLANK") + .forEach(position => { + const color = board[position]["color"]; + const pieceType = board[position]["pieceType"]; + document.getElementById(position) + .insertAdjacentHTML("beforeend", PIECES[`${color}_${pieceType}`]); + }); + } - (async function () { - const chessGame = await getChessGame(); - const board = chessGame["boardDto"]["board"]; - const turn = chessGame["turn"]; - const score = chessGame["score"]["scores"]; + function setTurn(turn) { + document.getElementById("turn_box") + .innerHTML = '

' + turn["color"] + "의 턴입니다." + '

'; + } - if (chessGame["normalStatus"] === false) { - alert("잘못된 명령입니다."); - return; - } - setBoard(board); - setTurn(turn); - setScore(score); - })(); + function setScore(score) { + document.getElementById("score") + .innerHTML = '

' + + "WHITE 팀의 점수는 " + score["WHITE"] + "점 입니다.\n" + + "BLACK 팀의 점수는 " + score["BLACK"] + "점 입니다." + + '

'; + } - function chooseFirstPosition(position) { - fetch(`http://localhost:4567/source?source=${position}`, {method: "POST"}) - .then(res => res.json()) - .then(data => { - startPosition = data.position; - console.log(data.normalStatus); - if (data.normalStatus === false) { - alert(data.exception); - startPosition = null; - return; - } - const positions = data.movable; - positions.forEach(position => { - document.getElementById(position) - .style - .backgroundColor = "rgba(255, 100, 0, 0.2)"; - }); + (async function () { + const chessGame = await getChessGame(); + const board = chessGame["boardDto"]["board"]; + const turn = chessGame["turn"]; + const score = chessGame["score"]["scores"]; - document.getElementById(position) - .style - .backgroundColor = "rgba(255, 200, 0, 0.2)"; - }); + if (chessGame["normalStatus"] === false) { + alert("잘못된 명령입니다."); + return; } + setBoard(board); + setTurn(turn); + setScore(score); + })(); - function chooseSecondPosition(position) { - fetch(`http://localhost:4567/destination?destination=${position}`, {method: "POST"}) - .then(res => res.json()) - .then(data => { - if (data.normalStatus === false) { - alert(data.exception); - return; - } - const source = startPosition; - const destination = data.position; - startPosition = null; + function chooseFirstPosition(position) { + fetch(`http://localhost:4567/source?source=${position}`, {method: "POST"}) + .then(res => res.json()) + .then(data => { + startPosition = data.position; + console.log(data.normalStatus); + if (data.normalStatus === false) { + alert(data.exception); + startPosition = null; + return; + } + const positions = data.movable; + positions.forEach(position => { + document.getElementById(position) + .style + .backgroundColor = "rgba(255, 100, 0, 0.2)"; + }); - if (source === destination) { - alert("이동을 취소합니다."); - } + document.getElementById(position) + .style + .backgroundColor = "rgba(255, 200, 0, 0.2)"; + }); + } - post_to_url("/board", {"source": source, "destination": destination}); - }); - } + function chooseSecondPosition(position) { + fetch(`http://localhost:4567/destination?destination=${position}`, {method: "POST"}) + .then(res => res.json()) + .then(data => { + if (data.normalStatus === false) { + alert(data.exception); + return; + } + const source = startPosition; + const destination = data.position; + startPosition = null; - document.querySelectorAll(".position").forEach( - element => { - element.addEventListener("click", (e) => { - let position = e.currentTarget.id; - e.preventDefault(); - if (startPosition == null) { - chooseFirstPosition(position); - } else { - chooseSecondPosition(position); - } - }); + if (source === destination) { + alert("이동을 취소합니다."); } - ); - function post_to_url(path, params) { - let form = document.createElement("form"); - form.setAttribute("method", "post"); - form.setAttribute("action", path); - for (let key in params) { - let hiddenField = document.createElement("input"); - hiddenField.setAttribute("type", "hidden"); - hiddenField.setAttribute("name", key); - hiddenField.setAttribute("value", params[key]); - form.appendChild(hiddenField); + post_to_url("/board", {"source": source, "destination": destination}); + }); + } + + document.querySelectorAll(".position").forEach( + element => { + element.addEventListener("click", (e) => { + let position = e.currentTarget.id; + e.preventDefault(); + if (startPosition == null) { + chooseFirstPosition(position); + } else { + chooseSecondPosition(position); } - document.body.appendChild(form); - form.submit(); + }); + } + ); + + function post_to_url(path, params) { + let form = document.createElement("form"); + form.setAttribute("method", "post"); + form.setAttribute("action", path); + for (let key in params) { + let hiddenField = document.createElement("input"); + hiddenField.setAttribute("type", "hidden"); + hiddenField.setAttribute("name", key); + hiddenField.setAttribute("value", params[key]); + form.appendChild(hiddenField); } + document.body.appendChild(form); + form.submit(); + } }; \ No newline at end of file From 940776c0b5dd830d2c59f48b2004835113fd5a2f Mon Sep 17 00:00:00 2001 From: toneyparky Date: Fri, 1 May 2020 20:30:11 +0900 Subject: [PATCH 13/22] =?UTF-8?q?feat:=20move=EC=99=80=20loading=20?= =?UTF-8?q?=EA=B4=80=EB=A0=A8=20api=EC=97=90=20gameId=EB=A5=BC=20=EC=9D=B4?= =?UTF-8?q?=EC=9A=A9=ED=95=98=EB=8F=84=EB=A1=9D=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SpringChessController id를 라우트에 추가 SpringDataJDBCChessService id를 이용해서 해당 게임 정보를 가져오도록 수정 chess.js id를 이용하여 리퀘스트를 보내도록 수정 --- .../controller/SpringChessController.java | 31 ++++++------- .../service/SpringDataJDBCChessService.java | 43 +++++-------------- src/main/resources/static/public/js/chess.js | 17 ++++---- 3 files changed, 32 insertions(+), 59 deletions(-) diff --git a/src/main/java/wooteco/chess/controller/SpringChessController.java b/src/main/java/wooteco/chess/controller/SpringChessController.java index 90368fb024..872b8f0fbe 100644 --- a/src/main/java/wooteco/chess/controller/SpringChessController.java +++ b/src/main/java/wooteco/chess/controller/SpringChessController.java @@ -12,7 +12,6 @@ import wooteco.chess.service.SpringDataJDBCChessService; import wooteco.chess.web.JsonTransformer; -import java.sql.SQLException; import java.util.HashMap; import java.util.Map; @@ -40,7 +39,7 @@ public String saveNewGame(@RequestBody Map param) { @GetMapping("/game/{id}") @ResponseBody - public ModelAndView startGame(@PathVariable Long id) { + public ModelAndView startGame() { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("chess"); modelAndView.addObject("normalStatus", NormalStatus.YES.isNormalStatus()); @@ -54,19 +53,12 @@ public String setBoard(@PathVariable Long id) { return JsonTransformer.toJson(chessGameDto); } - @GetMapping("/board") + @GetMapping("/board/{id}/source") @ResponseBody - public String setBoard() throws SQLException { - ChessGameDto chessGameDto = springDataJDBCChessService.setBoard(); - return JsonTransformer.toJson(chessGameDto); - } - - @GetMapping("/source") - @ResponseBody - public String getMovablePositions(@RequestParam String source) throws SQLException { + public String getMovablePositions2(@PathVariable Long id, @RequestParam String source) { Map model = new HashMap<>(); try { - MovablePositionsDto movablePositionsDto = springDataJDBCChessService.findMovablePositions(source); + MovablePositionsDto movablePositionsDto = springDataJDBCChessService.findMovablePositions(id, source); model.put("movable", movablePositionsDto.getMovablePositionNames()); model.put("position", movablePositionsDto.getPosition()); model.put("normalStatus", NormalStatus.YES.isNormalStatus()); @@ -78,11 +70,12 @@ public String getMovablePositions(@RequestParam String source) throws SQLExcepti } } - @GetMapping("/destination") + @GetMapping("/board/{id}/destination") @ResponseBody - public String checkMovable(@RequestParam String startPosition, @RequestParam String destination) { + public String checkMovable(@PathVariable Long id, @RequestParam String startPosition, + @RequestParam String destination) { Map model = new HashMap<>(); - MoveStatusDto moveStatusDto = springDataJDBCChessService.checkMovable( + MoveStatusDto moveStatusDto = springDataJDBCChessService.checkMovable(id, new MovingPosition(startPosition, destination)); model.put("normalStatus", moveStatusDto.getNormalStatus()); @@ -90,11 +83,11 @@ public String checkMovable(@RequestParam String startPosition, @RequestParam Str return JsonTransformer.toJson(model); } - @PostMapping("/board") - public ModelAndView saveHistory(@RequestBody MovingPosition movingPosition) throws SQLException { + @PostMapping("/board/{id}") + public ModelAndView saveHistory(@PathVariable Long id, @RequestBody MovingPosition movingPosition) { ModelAndView modelAndView = new ModelAndView(); - MoveStatusDto moveStatusDto = springDataJDBCChessService.move(movingPosition); + MoveStatusDto moveStatusDto = springDataJDBCChessService.move(id, movingPosition); if (moveStatusDto.getWinner().isNone()) { modelAndView.setViewName("chess"); return modelAndView; @@ -105,7 +98,7 @@ public ModelAndView saveHistory(@RequestBody MovingPosition movingPosition) thro return modelAndView; } - @GetMapping("/loading") + @GetMapping("/loading/{id}") public ModelAndView loadGame() { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("chess"); diff --git a/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java b/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java index 94fdaf80b6..5dd69c974a 100644 --- a/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java +++ b/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java @@ -17,7 +17,6 @@ import java.util.Collections; import java.util.List; import java.util.Set; -import java.util.UUID; import java.util.stream.Collectors; @Service @@ -32,14 +31,6 @@ public void clearHistory() { historyRepository.deleteAll(); } - public ChessGameDto setBoard() { - ChessGame chessGame = new ChessGame(); - - load(chessGame); - - return new ChessGameDto(new BoardDto(chessGame.getPieces()), chessGame.getTurn(), chessGame.calculateScore(), NormalStatus.YES.isNormalStatus()); - } - public ChessGameDto createGameBy(String gameName) { ChessGame chessGame = new ChessGame(); Long gameId = save(gameName); @@ -76,23 +67,9 @@ private List selectAllHistoryBy(Long id) { .collect(Collectors.toList())); } - private void load(ChessGame chessGame) { - List histories = selectAllHistory(); - - for (MovingPosition movingPosition : histories) { - chessGame.move(movingPosition); - } - } - - private List selectAllHistory() { - return Collections.unmodifiableList(historyRepository.findAll().stream() - .map(history -> new MovingPosition(history.getStart(), history.getEnd())) - .collect(Collectors.toList())); - } - - public MovablePositionsDto findMovablePositions(String source) { + public MovablePositionsDto findMovablePositions(Long id, String source) { ChessGame chessGame = new ChessGame(); - load(chessGame); + load(chessGame, id); List movablePositionNames = chessGame.findMovablePositionNames(source); @@ -100,11 +77,11 @@ public MovablePositionsDto findMovablePositions(String source) { } - public MoveStatusDto checkMovable(MovingPosition movingPosition) { + public MoveStatusDto checkMovable(Long id, MovingPosition movingPosition) { try { ChessGame chessGame = new ChessGame(); - load(chessGame); + load(chessGame, id); chessGame.move(movingPosition); return new MoveStatusDto(NormalStatus.YES.isNormalStatus()); } catch (IllegalArgumentException | UnsupportedOperationException | NullPointerException e) { @@ -112,9 +89,9 @@ public MoveStatusDto checkMovable(MovingPosition movingPosition) { } } - public MoveStatusDto move(MovingPosition movingPosition) { + public MoveStatusDto move(Long id, MovingPosition movingPosition) { ChessGame chessGame = new ChessGame(); - load(chessGame); + load(chessGame, id); chessGame.move(movingPosition); MoveStatusDto moveStatusDto = new MoveStatusDto(NormalStatus.YES.isNormalStatus()); @@ -123,13 +100,15 @@ public MoveStatusDto move(MovingPosition movingPosition) { moveStatusDto = new MoveStatusDto(NormalStatus.YES.isNormalStatus(), chessGame.getAliveKingColor()); } - insertHistory(movingPosition); + insertHistory(id, movingPosition); return moveStatusDto; } - private void insertHistory(MovingPosition movingPosition) { + private void insertHistory(Long id, MovingPosition movingPosition) { + Game game = gameRepository.findById(id).get(); // TODO: 2020/05/01 예외 처리 생각하기 History history = new History(movingPosition.getStart(), movingPosition.getEnd()); - historyRepository.save(history); + game.addHistory(history); + gameRepository.save(game); } } diff --git a/src/main/resources/static/public/js/chess.js b/src/main/resources/static/public/js/chess.js index 74316a8ff7..591fe681da 100644 --- a/src/main/resources/static/public/js/chess.js +++ b/src/main/resources/static/public/js/chess.js @@ -14,10 +14,12 @@ window.onload = function () { WHITE_WHITE_PAWN: ``, }; let startPosition = null; + let pathName; async function getChessGame() { - let pathName = window.location.pathname; - const response = await fetch(`http://localhost:8080/board/${pathName.substring(6)}`); + let path = window.location.pathname; + pathName = path.substring(path.lastIndexOf("/") + 1); + const response = await fetch(`http://localhost:8080/board/${pathName}`); return await response.json(); } @@ -51,7 +53,6 @@ window.onload = function () { } (async function () { - console.log("start!"); const chessGame = await getChessGame(); const board = await chessGame["boardDto"]["board"]; console.log(board); @@ -68,7 +69,7 @@ window.onload = function () { })(); function chooseFirstPosition(position) { - fetch(`http://localhost:8080/source?source=${position}`, + fetch(`http://localhost:8080/board/${pathName}/source?source=${position}`, {method: "GET"}) .then(res => res.json()) .then(data => { @@ -93,21 +94,21 @@ window.onload = function () { } function chooseSecondPosition(position) { - fetch(`http://localhost:8080/destination?destination=${position}&startPosition=${startPosition}`, + fetch(`http://localhost:8080/board/${pathName}/destination?destination=${position}&startPosition=${startPosition}`, {method: "GET"}) .then(res => res.json()) .then(async data => { if (data.normalStatus === false) { alert(data.exception); startPosition = null; - window.location.href = "/loading"; + window.location.href = `/loading/${pathName}`; return; } const source = startPosition; const destination = position; startPosition = null; - await fetch("http://localhost:8080/board", { + await fetch(`http://localhost:8080/board/${pathName}`, { method: "POST", body: JSON.stringify({ start: source, @@ -115,7 +116,7 @@ window.onload = function () { }), headers: {"Content-Type": "application/json"} }) - .then(window.location.href = "/loading"); + .then(window.location.href = `/loading/${pathName}`); }); } From fec4be25ea2ddf412a0d9fc04387a665831cfa2c Mon Sep 17 00:00:00 2001 From: toneyparky Date: Fri, 1 May 2020 22:18:13 +0900 Subject: [PATCH 14/22] =?UTF-8?q?feat:=20=EA=B2=8C=EC=9E=84=EC=9D=B4=20?= =?UTF-8?q?=EC=A2=85=EB=A3=8C=EB=90=98=EB=A9=B4=20=EA=B2=B0=EA=B3=BC=20?= =?UTF-8?q?=ED=8E=98=EC=9D=B4=EC=A7=80=EB=A1=9C=20=EB=84=98=EC=96=B4?= =?UTF-8?q?=EA=B0=80=EB=8A=94=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SpringChessController result get 라우트 구현 SpringDataJDBCChessService updateCanContinueToFalse를 사용 chess.js 종료시 result.hbs로 이동 --- .../controller/SpringChessController.java | 21 +++++++++---------- .../service/SpringDataJDBCChessService.java | 10 +++++---- src/main/resources/static/public/js/chess.js | 20 ++++++++++++++---- 3 files changed, 32 insertions(+), 19 deletions(-) diff --git a/src/main/java/wooteco/chess/controller/SpringChessController.java b/src/main/java/wooteco/chess/controller/SpringChessController.java index 872b8f0fbe..193fe38a66 100644 --- a/src/main/java/wooteco/chess/controller/SpringChessController.java +++ b/src/main/java/wooteco/chess/controller/SpringChessController.java @@ -84,18 +84,10 @@ public String checkMovable(@PathVariable Long id, @RequestParam String startPosi } @PostMapping("/board/{id}") - public ModelAndView saveHistory(@PathVariable Long id, @RequestBody MovingPosition movingPosition) { - ModelAndView modelAndView = new ModelAndView(); - + @ResponseBody + public String saveHistory(@PathVariable Long id, @RequestBody MovingPosition movingPosition) { MoveStatusDto moveStatusDto = springDataJDBCChessService.move(id, movingPosition); - if (moveStatusDto.getWinner().isNone()) { - modelAndView.setViewName("chess"); - return modelAndView; - } - modelAndView.setViewName("result"); - modelAndView.addObject("winner", moveStatusDto.getWinner()); - springDataJDBCChessService.clearHistory(); - return modelAndView; + return JsonTransformer.toJson(moveStatusDto); } @GetMapping("/loading/{id}") @@ -103,7 +95,14 @@ public ModelAndView loadGame() { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("chess"); modelAndView.addObject("normalStatus", NormalStatus.YES.isNormalStatus()); + return modelAndView; + } + @GetMapping("/result/{winner}") + public ModelAndView showResult(@PathVariable String winner) { + ModelAndView modelAndView = new ModelAndView(); + modelAndView.setViewName("result"); + modelAndView.addObject("winner", winner); return modelAndView; } } \ No newline at end of file diff --git a/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java b/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java index 5dd69c974a..819e7cc9f5 100644 --- a/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java +++ b/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java @@ -27,10 +27,6 @@ public class SpringDataJDBCChessService { @Autowired private GameRepository gameRepository; - public void clearHistory() { - historyRepository.deleteAll(); - } - public ChessGameDto createGameBy(String gameName) { ChessGame chessGame = new ChessGame(); Long gameId = save(gameName); @@ -97,6 +93,7 @@ public MoveStatusDto move(Long id, MovingPosition movingPosition) { MoveStatusDto moveStatusDto = new MoveStatusDto(NormalStatus.YES.isNormalStatus()); if (chessGame.isKingDead()) { + updateCanContinueToFalse(id); moveStatusDto = new MoveStatusDto(NormalStatus.YES.isNormalStatus(), chessGame.getAliveKingColor()); } @@ -105,6 +102,11 @@ public MoveStatusDto move(Long id, MovingPosition movingPosition) { return moveStatusDto; } + private void updateCanContinueToFalse(Long id) { + Game game = gameRepository.findById(id).get(); // TODO: 2020/05/01 예외 처리 수정 + gameRepository.save(new Game(game.getId(), game.getName(), false)); + } + private void insertHistory(Long id, MovingPosition movingPosition) { Game game = gameRepository.findById(id).get(); // TODO: 2020/05/01 예외 처리 생각하기 History history = new History(movingPosition.getStart(), movingPosition.getEnd()); diff --git a/src/main/resources/static/public/js/chess.js b/src/main/resources/static/public/js/chess.js index 591fe681da..8320686247 100644 --- a/src/main/resources/static/public/js/chess.js +++ b/src/main/resources/static/public/js/chess.js @@ -96,8 +96,10 @@ window.onload = function () { function chooseSecondPosition(position) { fetch(`http://localhost:8080/board/${pathName}/destination?destination=${position}&startPosition=${startPosition}`, {method: "GET"}) - .then(res => res.json()) - .then(async data => { + .then(function (response) { + return response.json(); + }) + .then(data => { if (data.normalStatus === false) { alert(data.exception); startPosition = null; @@ -108,7 +110,7 @@ window.onload = function () { const destination = position; startPosition = null; - await fetch(`http://localhost:8080/board/${pathName}`, { + fetch(`http://localhost:8080/board/${pathName}`, { method: "POST", body: JSON.stringify({ start: source, @@ -116,7 +118,17 @@ window.onload = function () { }), headers: {"Content-Type": "application/json"} }) - .then(window.location.href = `/loading/${pathName}`); + .then(function (winnerResponse) { + return winnerResponse.json(); + }) + .then(winnerData => { + console.log(winnerData); + if (winnerData["winner"] !== "NONE") { + let winnerTeam = winnerData["winner"]; + return location.href = `/result/${winnerTeam}`; + } + location.href= `/loading/${pathName}`; + }) }); } From c742427f04603c39a0bc25cc185530584caf7c05 Mon Sep 17 00:00:00 2001 From: toneyparky Date: Mon, 4 May 2020 11:56:01 +0900 Subject: [PATCH 15/22] =?UTF-8?q?feat:=20=EC=A7=84=ED=96=89=EA=B0=80?= =?UTF-8?q?=EB=8A=A5=ED=95=9C=20=EA=B2=8C=EC=9E=84=20=EB=AA=A9=EB=A1=9D?= =?UTF-8?q?=EC=9D=84=20=EB=B3=B4=EC=97=AC=EC=A3=BC=EB=8A=94=20=EA=B8=B0?= =?UTF-8?q?=EB=8A=A5=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SpringChessController /games get 라우트 추가 GamesDto 추가 GameRepository findAvailableGames로 메서드명 변경 SpringDataJDBCChessService selectAvailableGames 메서드 추가 index.js 게임 목록을 가져와 보여주는 기능 추가 --- .../controller/SpringChessController.java | 162 +++++++++--------- src/main/java/wooteco/chess/dto/GamesDto.java | 16 ++ .../wooteco/chess/entity/GameRepository.java | 4 +- .../service/SpringDataJDBCChessService.java | 16 +- .../wooteco/chess/web/ConnectionManager.java | 48 +++--- .../wooteco/chess/web/JsonTransformer.java | 12 +- src/main/resources/static/public/js/chess.js | 2 +- src/main/resources/static/public/js/index.js | 18 ++ .../chess/entity/GameRepositoryTest.java | 4 +- 9 files changed, 162 insertions(+), 120 deletions(-) create mode 100644 src/main/java/wooteco/chess/dto/GamesDto.java diff --git a/src/main/java/wooteco/chess/controller/SpringChessController.java b/src/main/java/wooteco/chess/controller/SpringChessController.java index 193fe38a66..8ec0229597 100644 --- a/src/main/java/wooteco/chess/controller/SpringChessController.java +++ b/src/main/java/wooteco/chess/controller/SpringChessController.java @@ -7,6 +7,7 @@ import wooteco.chess.domain.game.NormalStatus; import wooteco.chess.domain.position.MovingPosition; import wooteco.chess.dto.ChessGameDto; +import wooteco.chess.dto.GamesDto; import wooteco.chess.dto.MovablePositionsDto; import wooteco.chess.dto.MoveStatusDto; import wooteco.chess.service.SpringDataJDBCChessService; @@ -17,92 +18,99 @@ @Controller public class SpringChessController { - @Autowired - private SpringDataJDBCChessService springDataJDBCChessService; + @Autowired + private SpringDataJDBCChessService springDataJDBCChessService; - @GetMapping("/") - public ModelAndView routeMainPage() { - ModelAndView modelAndView = new ModelAndView(); - modelAndView.setViewName("index"); - modelAndView.addObject("normalStatus", NormalStatus.YES.isNormalStatus()); - return modelAndView; - } + @GetMapping("/") + public ModelAndView routeMainPage() { + ModelAndView modelAndView = new ModelAndView(); + modelAndView.setViewName("index"); + modelAndView.addObject("normalStatus", NormalStatus.YES.isNormalStatus()); + return modelAndView; + } - @PostMapping("/new") - @ResponseBody - public String saveNewGame(@RequestBody Map param) { - System.out.println(param.get("gameName")); - ChessGameDto chessGameDto = springDataJDBCChessService.createGameBy((String) param.get("gameName")); + @GetMapping("/games") + @ResponseBody + public String showGames() { + GamesDto games = springDataJDBCChessService.selectAvailableGames(); + return JsonTransformer.toJson(games); + } - return JsonTransformer.toJson(chessGameDto); - } + @PostMapping("/new") + @ResponseBody + public String saveNewGame(@RequestBody Map param) { + System.out.println(param.get("gameName")); + ChessGameDto chessGameDto = springDataJDBCChessService.createGameBy((String) param.get("gameName")); - @GetMapping("/game/{id}") - @ResponseBody - public ModelAndView startGame() { - ModelAndView modelAndView = new ModelAndView(); - modelAndView.setViewName("chess"); - modelAndView.addObject("normalStatus", NormalStatus.YES.isNormalStatus()); - return modelAndView; - } + return JsonTransformer.toJson(chessGameDto); + } - @GetMapping("/board/{id}") - @ResponseBody - public String setBoard(@PathVariable Long id) { - ChessGameDto chessGameDto = springDataJDBCChessService.setBoardBy(id); - return JsonTransformer.toJson(chessGameDto); - } + @GetMapping("/game/{id}") + @ResponseBody + public ModelAndView startGame() { + ModelAndView modelAndView = new ModelAndView(); + modelAndView.setViewName("chess"); + modelAndView.addObject("normalStatus", NormalStatus.YES.isNormalStatus()); + return modelAndView; + } - @GetMapping("/board/{id}/source") - @ResponseBody - public String getMovablePositions2(@PathVariable Long id, @RequestParam String source) { - Map model = new HashMap<>(); - try { - MovablePositionsDto movablePositionsDto = springDataJDBCChessService.findMovablePositions(id, source); - model.put("movable", movablePositionsDto.getMovablePositionNames()); - model.put("position", movablePositionsDto.getPosition()); - model.put("normalStatus", NormalStatus.YES.isNormalStatus()); - return JsonTransformer.toJson(model); - } catch (IllegalArgumentException | UnsupportedOperationException | NullPointerException e) { - model.put("normalStatus", NormalStatus.NO.isNormalStatus()); - model.put("exception", e.getMessage()); - return JsonTransformer.toJson(model); - } - } + @GetMapping("/board/{id}") + @ResponseBody + public String setBoard(@PathVariable Long id) { + ChessGameDto chessGameDto = springDataJDBCChessService.setBoardBy(id); + return JsonTransformer.toJson(chessGameDto); + } - @GetMapping("/board/{id}/destination") - @ResponseBody - public String checkMovable(@PathVariable Long id, @RequestParam String startPosition, - @RequestParam String destination) { - Map model = new HashMap<>(); - MoveStatusDto moveStatusDto = springDataJDBCChessService.checkMovable(id, - new MovingPosition(startPosition, destination)); + @GetMapping("/board/{id}/source") + @ResponseBody + public String getMovablePositions2(@PathVariable Long id, @RequestParam String source) { + Map model = new HashMap<>(); + try { + MovablePositionsDto movablePositionsDto = springDataJDBCChessService.findMovablePositions(id, source); + model.put("movable", movablePositionsDto.getMovablePositionNames()); + model.put("position", movablePositionsDto.getPosition()); + model.put("normalStatus", NormalStatus.YES.isNormalStatus()); + return JsonTransformer.toJson(model); + } catch (IllegalArgumentException | UnsupportedOperationException | NullPointerException e) { + model.put("normalStatus", NormalStatus.NO.isNormalStatus()); + model.put("exception", e.getMessage()); + return JsonTransformer.toJson(model); + } + } - model.put("normalStatus", moveStatusDto.getNormalStatus()); - model.put("exception", moveStatusDto.getException()); - return JsonTransformer.toJson(model); - } + @GetMapping("/board/{id}/destination") + @ResponseBody + public String checkMovable(@PathVariable Long id, @RequestParam String startPosition, + @RequestParam String destination) { + Map model = new HashMap<>(); + MoveStatusDto moveStatusDto = springDataJDBCChessService.checkMovable(id, + new MovingPosition(startPosition, destination)); - @PostMapping("/board/{id}") - @ResponseBody - public String saveHistory(@PathVariable Long id, @RequestBody MovingPosition movingPosition) { - MoveStatusDto moveStatusDto = springDataJDBCChessService.move(id, movingPosition); - return JsonTransformer.toJson(moveStatusDto); - } + model.put("normalStatus", moveStatusDto.getNormalStatus()); + model.put("exception", moveStatusDto.getException()); + return JsonTransformer.toJson(model); + } - @GetMapping("/loading/{id}") - public ModelAndView loadGame() { - ModelAndView modelAndView = new ModelAndView(); - modelAndView.setViewName("chess"); - modelAndView.addObject("normalStatus", NormalStatus.YES.isNormalStatus()); - return modelAndView; - } + @PostMapping("/board/{id}") + @ResponseBody + public String saveHistory(@PathVariable Long id, @RequestBody MovingPosition movingPosition) { + MoveStatusDto moveStatusDto = springDataJDBCChessService.move(id, movingPosition); + return JsonTransformer.toJson(moveStatusDto); + } - @GetMapping("/result/{winner}") - public ModelAndView showResult(@PathVariable String winner) { - ModelAndView modelAndView = new ModelAndView(); - modelAndView.setViewName("result"); - modelAndView.addObject("winner", winner); - return modelAndView; - } + @GetMapping("/loading/{id}") + public ModelAndView loadGame() { + ModelAndView modelAndView = new ModelAndView(); + modelAndView.setViewName("chess"); + modelAndView.addObject("normalStatus", NormalStatus.YES.isNormalStatus()); + return modelAndView; + } + + @GetMapping("/result/{winner}") + public ModelAndView showResult(@PathVariable String winner) { + ModelAndView modelAndView = new ModelAndView(); + modelAndView.setViewName("result"); + modelAndView.addObject("winner", winner); + return modelAndView; + } } \ No newline at end of file diff --git a/src/main/java/wooteco/chess/dto/GamesDto.java b/src/main/java/wooteco/chess/dto/GamesDto.java new file mode 100644 index 0000000000..f10528a7b7 --- /dev/null +++ b/src/main/java/wooteco/chess/dto/GamesDto.java @@ -0,0 +1,16 @@ +package wooteco.chess.dto; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class GamesDto { + private Map games = new LinkedHashMap<>(); + + public GamesDto(Map games) { + this.games = games; + } + + public Map getGames() { + return games; + } +} diff --git a/src/main/java/wooteco/chess/entity/GameRepository.java b/src/main/java/wooteco/chess/entity/GameRepository.java index 7436384b1e..889f9ea0f4 100644 --- a/src/main/java/wooteco/chess/entity/GameRepository.java +++ b/src/main/java/wooteco/chess/entity/GameRepository.java @@ -2,14 +2,12 @@ import org.springframework.data.jdbc.repository.query.Query; import org.springframework.data.repository.CrudRepository; -import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface GameRepository extends CrudRepository { - @Override @Query("SELECT * FROM game WHERE can_continue = true") - List findAll(); + List findAvailableGames(); } diff --git a/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java b/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java index 819e7cc9f5..45e2b45398 100644 --- a/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java +++ b/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java @@ -5,18 +5,13 @@ import wooteco.chess.domain.game.ChessGame; import wooteco.chess.domain.game.NormalStatus; import wooteco.chess.domain.position.MovingPosition; -import wooteco.chess.dto.BoardDto; -import wooteco.chess.dto.ChessGameDto; -import wooteco.chess.dto.MovablePositionsDto; -import wooteco.chess.dto.MoveStatusDto; +import wooteco.chess.dto.*; import wooteco.chess.entity.Game; import wooteco.chess.entity.GameRepository; import wooteco.chess.entity.History; import wooteco.chess.entity.HistoryRepository; -import java.util.Collections; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.stream.Collectors; @Service @@ -113,4 +108,11 @@ private void insertHistory(Long id, MovingPosition movingPosition) { game.addHistory(history); gameRepository.save(game); } + + public GamesDto selectAvailableGames() { + Map games = gameRepository.findAvailableGames().stream() + .collect(Collectors.toMap(game -> game.getId(), game -> game.getName(), + (e1, e2) -> e1, LinkedHashMap::new)); + return new GamesDto(games); + } } diff --git a/src/main/java/wooteco/chess/web/ConnectionManager.java b/src/main/java/wooteco/chess/web/ConnectionManager.java index 4450ac87ba..acbf1d5f13 100644 --- a/src/main/java/wooteco/chess/web/ConnectionManager.java +++ b/src/main/java/wooteco/chess/web/ConnectionManager.java @@ -5,31 +5,31 @@ import java.sql.SQLException; public class ConnectionManager { - public Connection getConnection() { - Connection con = null; - String server = "localhost:13306"; // MySQL 서버 주소 - String database = "chess"; // MySQL DATABASE 이름 - String option = "?useSSL=false&serverTimezone=UTC"; - String userName = "root"; // MySQL 서버 아이디 - String password = "root"; // MySQL 서버 비밀번호 + public Connection getConnection() { + Connection con = null; + String server = "localhost:13306"; // MySQL 서버 주소 + String database = "chess"; // MySQL DATABASE 이름 + String option = "?useSSL=false&serverTimezone=UTC"; + String userName = "root"; // MySQL 서버 아이디 + String password = "root"; // MySQL 서버 비밀번호 - // 드라이버 로딩 - try { - Class.forName("com.mysql.cj.jdbc.Driver"); - } catch (ClassNotFoundException e) { - System.err.println(" !! JDBC Driver load 오류: " + e.getMessage()); - e.printStackTrace(); - } + // 드라이버 로딩 + try { + Class.forName("com.mysql.cj.jdbc.Driver"); + } catch (ClassNotFoundException e) { + System.err.println(" !! JDBC Driver load 오류: " + e.getMessage()); + e.printStackTrace(); + } - // 드라이버 연결 - try { - con = DriverManager.getConnection("jdbc:mysql://" + server + "/" + database + option, userName, password); - System.out.println("정상적으로 연결되었습니다."); - } catch (SQLException e) { - System.err.println("연결 오류:" + e.getMessage()); - e.printStackTrace(); - } + // 드라이버 연결 + 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; - } + return con; + } } diff --git a/src/main/java/wooteco/chess/web/JsonTransformer.java b/src/main/java/wooteco/chess/web/JsonTransformer.java index 3fd1eede18..de6ea09517 100644 --- a/src/main/java/wooteco/chess/web/JsonTransformer.java +++ b/src/main/java/wooteco/chess/web/JsonTransformer.java @@ -5,11 +5,11 @@ public class JsonTransformer { - public static String toJson(Object object) { - return new Gson().toJson(object); - } + public static String toJson(Object object) { + return new Gson().toJson(object); + } - public static ResponseTransformer json() { - return JsonTransformer::toJson; - } + public static ResponseTransformer json() { + return JsonTransformer::toJson; + } } diff --git a/src/main/resources/static/public/js/chess.js b/src/main/resources/static/public/js/chess.js index 8320686247..9510e0167e 100644 --- a/src/main/resources/static/public/js/chess.js +++ b/src/main/resources/static/public/js/chess.js @@ -127,7 +127,7 @@ window.onload = function () { let winnerTeam = winnerData["winner"]; return location.href = `/result/${winnerTeam}`; } - location.href= `/loading/${pathName}`; + location.href = `/loading/${pathName}`; }) }); } diff --git a/src/main/resources/static/public/js/index.js b/src/main/resources/static/public/js/index.js index f3927168f2..fa631f14c5 100644 --- a/src/main/resources/static/public/js/index.js +++ b/src/main/resources/static/public/js/index.js @@ -17,4 +17,22 @@ window.onload = function () { window.location.href = `/game/${gameId}`; }); }); + + function showGames() { + fetch("http://localhost:8080/games") + .then(res => res.json()) + .then(games => { + const loadingDiv = document.querySelector("#loading"); + loadingDiv.innerHTML += generateGames(games, Object.keys(games["games"])); + }); + } + + function generateGames(games, keys) { + console.log(games); + console.log(keys); + return keys.map(key => ``) + .join(""); + } + + showGames(); }; \ No newline at end of file diff --git a/src/test/java/wooteco/chess/entity/GameRepositoryTest.java b/src/test/java/wooteco/chess/entity/GameRepositoryTest.java index ea325e91a1..25e82aa4ef 100644 --- a/src/test/java/wooteco/chess/entity/GameRepositoryTest.java +++ b/src/test/java/wooteco/chess/entity/GameRepositoryTest.java @@ -35,12 +35,12 @@ void save_normal_test() { @DisplayName("게임 목록 중 진행중인 게임 조회 기능 구현") @Test - void selectAll_test() { + void findAvailableGames_test() { Game firstGame = gameRepository.save(new Game(firstGameName, true)); Game secondGame = gameRepository.save(new Game("secondGameName", true)); Game thirdGame = gameRepository.save(new Game("thirdGameName", false)); - List games = gameRepository.findAll(); + List games = gameRepository.findAvailableGames(); assertThat(games).contains(firstGame, secondGame); assertThat(games).doesNotContain(thirdGame); From a7e61d69262bb61b5df220c961288094783ccdd5 Mon Sep 17 00:00:00 2001 From: toneyparky Date: Mon, 4 May 2020 12:13:31 +0900 Subject: [PATCH 16/22] =?UTF-8?q?feat:=20=EA=B2=8C=EC=9E=84=20=EC=A4=91=20?= =?UTF-8?q?=EB=82=98=EA=B0=80=EA=B8=B0=20=EA=B8=B0=EB=8A=A5=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 chess.hbs 나가기 링크 추가 --- src/main/resources/templates/chess.hbs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/resources/templates/chess.hbs b/src/main/resources/templates/chess.hbs index e9643f7998..ab6f08215a 100644 --- a/src/main/resources/templates/chess.hbs +++ b/src/main/resources/templates/chess.hbs @@ -98,6 +98,9 @@

+
+ 나가기 +
From 671275c50ceeb9daac59f80cc22dea14e637f910 Mon Sep 17 00:00:00 2001 From: toneyparky Date: Mon, 4 May 2020 12:14:26 +0900 Subject: [PATCH 17/22] =?UTF-8?q?refactor:=20=EC=82=AC=EC=9A=A9=ED=95=98?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EB=8A=94=20=EB=A0=88=ED=8F=AC=EC=A7=80?= =?UTF-8?q?=ED=86=A0=EB=A6=AC=20=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SpringDataJDBCChessService 리팩토링에 따른 수정 HistoryRepository.java 삭제 --- .../java/wooteco/chess/entity/HistoryRepository.java | 12 ------------ .../chess/service/SpringDataJDBCChessService.java | 4 ---- 2 files changed, 16 deletions(-) delete mode 100644 src/main/java/wooteco/chess/entity/HistoryRepository.java diff --git a/src/main/java/wooteco/chess/entity/HistoryRepository.java b/src/main/java/wooteco/chess/entity/HistoryRepository.java deleted file mode 100644 index 7ba2f22cbc..0000000000 --- a/src/main/java/wooteco/chess/entity/HistoryRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package wooteco.chess.entity; - -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -public interface HistoryRepository extends CrudRepository { - @Override - List findAll(); -} diff --git a/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java b/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java index 45e2b45398..878a90c26c 100644 --- a/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java +++ b/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java @@ -9,16 +9,12 @@ import wooteco.chess.entity.Game; import wooteco.chess.entity.GameRepository; import wooteco.chess.entity.History; -import wooteco.chess.entity.HistoryRepository; import java.util.*; import java.util.stream.Collectors; @Service public class SpringDataJDBCChessService { - @Autowired - private HistoryRepository historyRepository; - @Autowired private GameRepository gameRepository; From c8321e549c0b31e806f67bcc4ac319d9d1d91886 Mon Sep 17 00:00:00 2001 From: toneyparky Date: Mon, 4 May 2020 12:45:08 +0900 Subject: [PATCH 18/22] =?UTF-8?q?style:=20index.hbs=20=EB=B7=B0=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../resources/static/public/css/index.css | 40 ++++++++++++++++++- src/main/resources/static/public/js/index.js | 6 +-- src/main/resources/templates/index.hbs | 17 +++++++- 3 files changed, 55 insertions(+), 8 deletions(-) diff --git a/src/main/resources/static/public/css/index.css b/src/main/resources/static/public/css/index.css index 76f77421f2..5dcc04b9e0 100644 --- a/src/main/resources/static/public/css/index.css +++ b/src/main/resources/static/public/css/index.css @@ -1,3 +1,20 @@ +@import url(//fonts.googleapis.com/css?family=Yanone+Kaffeesatz); +@import url(//fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic); +@import url(//fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic); +@import url(//fonts.googleapis.com/earlyaccess/hanna.css); + +@font-face { + font-family: "BMHANNAAir"; + src: url("https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_four@1.0/BMHANNAAir.woff") format("woff"); + font-weight: bold; + font-style: normal; +} + +* { + font-family: BMHANNAAir; + font-size: 30px; +} + h1 { color: blue; font-size: 48px; @@ -8,8 +25,12 @@ h1 { text-align: center; } -#new a { - font-size: 32px; +#start-btn { + width: 200px; + height: 100px; + border-radius: 5px; + border: solid 1px; + font-size: 20px; } #loading { @@ -18,4 +39,19 @@ h1 { #loading a { font-size: 32px; +} + +#loading-table { + border: 1px solid black; + margin: auto; + text-align: center; + margin-top: 2em; +} + +#loading-table th, +#loading-table td { + border: 1px solid black; + height: 50px; + width: 50px; + text-align: center; } \ No newline at end of file diff --git a/src/main/resources/static/public/js/index.js b/src/main/resources/static/public/js/index.js index fa631f14c5..1eb36feb28 100644 --- a/src/main/resources/static/public/js/index.js +++ b/src/main/resources/static/public/js/index.js @@ -22,15 +22,13 @@ window.onload = function () { fetch("http://localhost:8080/games") .then(res => res.json()) .then(games => { - const loadingDiv = document.querySelector("#loading"); + const loadingDiv = document.querySelector("#loading-table > tbody"); loadingDiv.innerHTML += generateGames(games, Object.keys(games["games"])); }); } function generateGames(games, keys) { - console.log(games); - console.log(keys); - return keys.map(key => ``) + return keys.map(key => `${key}${games["games"][key]}`) .join(""); } diff --git a/src/main/resources/templates/index.hbs b/src/main/resources/templates/index.hbs index 976d1b5d0c..d6f130b9d6 100644 --- a/src/main/resources/templates/index.hbs +++ b/src/main/resources/templates/index.hbs @@ -8,11 +8,24 @@

체스게임

- +
- + + + + + + + + + +
+ 게임 아이디 + + 게임 이름 +
From 819034e60eb5fe0a82ae3b6c06636a92a8f59576 Mon Sep 17 00:00:00 2001 From: toneyparky Date: Mon, 4 May 2020 15:31:35 +0900 Subject: [PATCH 19/22] =?UTF-8?q?style:=20chess.hbs,=20result.hbs=20?= =?UTF-8?q?=EB=B7=B0=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../resources/static/public/css/chess.css | 22 +++++++++++++++++ .../resources/static/public/css/index.css | 3 +-- .../resources/static/public/css/result.css | 24 +++++++++++++++++++ src/main/resources/templates/chess.hbs | 6 ++--- src/main/resources/templates/result.hbs | 4 ++-- 5 files changed, 52 insertions(+), 7 deletions(-) diff --git a/src/main/resources/static/public/css/chess.css b/src/main/resources/static/public/css/chess.css index 28f35f6d4a..90f66f9f59 100644 --- a/src/main/resources/static/public/css/chess.css +++ b/src/main/resources/static/public/css/chess.css @@ -1,3 +1,20 @@ +@import url(//fonts.googleapis.com/css?family=Yanone+Kaffeesatz); +@import url(//fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic); +@import url(//fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic); +@import url(//fonts.googleapis.com/earlyaccess/hanna.css); + +@font-face { + font-family: "BMHANNAAir"; + src: url("https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_four@1.0/BMHANNAAir.woff") format("woff"); + font-weight: bold; + font-style: normal; +} + +* { + font-family: BMHANNAAir; + font-size: 30px; +} + .title { justify-content: center; background-color: gray; @@ -56,3 +73,8 @@ height: 20px; padding: 0; } + +.exit { + margin: 8px auto auto; + text-align: center; +} diff --git a/src/main/resources/static/public/css/index.css b/src/main/resources/static/public/css/index.css index 5dcc04b9e0..72328f4380 100644 --- a/src/main/resources/static/public/css/index.css +++ b/src/main/resources/static/public/css/index.css @@ -43,9 +43,8 @@ h1 { #loading-table { border: 1px solid black; - margin: auto; text-align: center; - margin-top: 2em; + margin: 2em auto auto; } #loading-table th, diff --git a/src/main/resources/static/public/css/result.css b/src/main/resources/static/public/css/result.css index c69384af46..7fa9d95242 100644 --- a/src/main/resources/static/public/css/result.css +++ b/src/main/resources/static/public/css/result.css @@ -1,10 +1,34 @@ +@import url(//fonts.googleapis.com/css?family=Yanone+Kaffeesatz); +@import url(//fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic); +@import url(//fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic); +@import url(//fonts.googleapis.com/earlyaccess/hanna.css); + +@font-face { + font-family: "BMHANNAAir"; + src: url("https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_four@1.0/BMHANNAAir.woff") format("woff"); + font-weight: bold; + font-style: normal; +} + +* { + font-family: BMHANNAAir; + font-size: 30px; +} + .result { margin: 0 auto; text-align: center; + margin-top: 2em; } .result p { font-size: 32px; + margin: 0 auto; +} + +.result button { + font-size: 32px; + margin: 0 auto; } #go-main { diff --git a/src/main/resources/templates/chess.hbs b/src/main/resources/templates/chess.hbs index ab6f08215a..09ad01358c 100644 --- a/src/main/resources/templates/chess.hbs +++ b/src/main/resources/templates/chess.hbs @@ -98,11 +98,11 @@

-
- 나가기 -
+ \ No newline at end of file diff --git a/src/main/resources/templates/result.hbs b/src/main/resources/templates/result.hbs index 2506a1d37d..b0dd35c68f 100644 --- a/src/main/resources/templates/result.hbs +++ b/src/main/resources/templates/result.hbs @@ -3,14 +3,14 @@ Chess Game Result - +

{{winner}}팀 승리!

\ No newline at end of file From 485b2b8f0384c2d882f679c4c72603dd275fee9a Mon Sep 17 00:00:00 2001 From: toneyparky Date: Mon, 4 May 2020 15:33:34 +0900 Subject: [PATCH 20/22] =?UTF-8?q?fix:=20=EA=B2=8C=EC=9E=84=20=EC=9D=B4?= =?UTF-8?q?=EB=A6=84=EC=9D=84=20=EC=9E=85=EB=A0=A5=ED=95=98=EC=A7=80=20?= =?UTF-8?q?=EC=95=8A=EC=9C=BC=EB=A9=B4=20=EB=B9=88=20=EB=B3=B4=EB=93=9C?= =?UTF-8?q?=EB=A1=9C=20=EB=84=98=EC=96=B4=EA=B0=80=EB=8A=94=20=EB=B2=84?= =?UTF-8?q?=EA=B7=B8=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/static/public/js/index.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/resources/static/public/js/index.js b/src/main/resources/static/public/js/index.js index 1eb36feb28..600da704b1 100644 --- a/src/main/resources/static/public/js/index.js +++ b/src/main/resources/static/public/js/index.js @@ -1,6 +1,10 @@ window.onload = function () { document.querySelector("#new").addEventListener("click", () => { let gameName = prompt("게임 이름을 입력하세요."); + if (!gameName) { + alert("게임 이름을 입력하지 않으셨습니다."); + return; + } fetch("http://localhost:8080/new", { method: "POST", body: JSON.stringify({ From 7247b44d3aba91ecb8dc7cf2871f1647a7ab4634 Mon Sep 17 00:00:00 2001 From: toneyparky Date: Mon, 4 May 2020 15:56:55 +0900 Subject: [PATCH 21/22] =?UTF-8?q?style:=20=ED=94=84=EB=A1=9C=EC=A0=9D?= =?UTF-8?q?=ED=8A=B8=20=EC=A0=84=EC=B2=B4=20=ED=8C=8C=EC=9D=BC=20=EC=BB=A8?= =?UTF-8?q?=EB=B2=A4=EC=85=98=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 1 - .../controller/SparkChessController.java | 6 +- .../controller/SpringChessController.java | 2 +- src/main/java/wooteco/chess/dto/BoardDto.java | 3 +- .../java/wooteco/chess/dto/ChessGameDto.java | 9 +- .../chess/dto/DestinationPositionDto.java | 4 +- src/main/java/wooteco/chess/dto/GamesDto.java | 6 +- .../chess/dto/MovablePositionsDto.java | 7 +- .../java/wooteco/chess/dto/MoveStatusDto.java | 6 +- src/main/java/wooteco/chess/entity/Game.java | 3 +- .../chess/service/SparkChessService.java | 6 +- .../chess/service/SpringChessService.java | 86 ------------------- .../service/SpringDataJDBCChessService.java | 3 +- .../wooteco/chess/web/ConnectionManager.java | 3 +- src/main/resources/application.properties | 1 - 15 files changed, 32 insertions(+), 114 deletions(-) delete mode 100644 src/main/java/wooteco/chess/service/SpringChessService.java diff --git a/build.gradle b/build.gradle index a234ac906d..9c9b7bbd27 100644 --- a/build.gradle +++ b/build.gradle @@ -20,7 +20,6 @@ dependencies { implementation 'net.rakugakibox.spring.boot:logback-access-spring-boot-starter:2.7.1' implementation 'pl.allegro.tech.boot:handlebars-spring-boot-starter:0.3.1' implementation 'com.google.code.gson:gson:2.8.6' - implementation 'com.google.code.gson:gson:2.8.6' compile('com.sparkjava:spark-core:2.9.0') compile('com.sparkjava:spark-template-handlebars:2.7.1') compile('ch.qos.logback:logback-classic:1.2.3') diff --git a/src/main/java/wooteco/chess/controller/SparkChessController.java b/src/main/java/wooteco/chess/controller/SparkChessController.java index 67b06f15ef..fc9e0d2bf3 100644 --- a/src/main/java/wooteco/chess/controller/SparkChessController.java +++ b/src/main/java/wooteco/chess/controller/SparkChessController.java @@ -70,7 +70,8 @@ private String postBoard(Request req, Response res) { Map model = new HashMap<>(); try { - MoveStatusDto moveStatusDto = sparkChessService.move(new MovingPosition(req.queryParams("source"), req.queryParams("destination"))); + MoveStatusDto moveStatusDto = sparkChessService.move(new MovingPosition(req.queryParams("source"), + req.queryParams("destination"))); model.put("normalStatus", moveStatusDto.getNormalStatus()); model.put("winner", moveStatusDto.getWinner()); @@ -108,7 +109,8 @@ private Map getMovablePositions(Request req, Response res) throw private Map move(Request req, Response res) { Map model = new HashMap<>(); - DestinationPositionDto destinationPositionDto = sparkChessService.chooseDestinationPosition(req.queryParams("destination")); + DestinationPositionDto destinationPositionDto = sparkChessService.chooseDestinationPosition( + req.queryParams("destination")); model.put("normalStatus", destinationPositionDto.getNormalStatus().isNormalStatus()); model.put("position", destinationPositionDto.getPosition()); diff --git a/src/main/java/wooteco/chess/controller/SpringChessController.java b/src/main/java/wooteco/chess/controller/SpringChessController.java index 8ec0229597..1cd7040d36 100644 --- a/src/main/java/wooteco/chess/controller/SpringChessController.java +++ b/src/main/java/wooteco/chess/controller/SpringChessController.java @@ -63,7 +63,7 @@ public String setBoard(@PathVariable Long id) { @GetMapping("/board/{id}/source") @ResponseBody - public String getMovablePositions2(@PathVariable Long id, @RequestParam String source) { + public String getMovablePositions(@PathVariable Long id, @RequestParam String source) { Map model = new HashMap<>(); try { MovablePositionsDto movablePositionsDto = springDataJDBCChessService.findMovablePositions(id, source); diff --git a/src/main/java/wooteco/chess/dto/BoardDto.java b/src/main/java/wooteco/chess/dto/BoardDto.java index 6fa8de5de8..e0acf4c791 100644 --- a/src/main/java/wooteco/chess/dto/BoardDto.java +++ b/src/main/java/wooteco/chess/dto/BoardDto.java @@ -4,6 +4,7 @@ import wooteco.chess.domain.piece.pieces.Pieces; import wooteco.chess.domain.position.Position; +import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -17,6 +18,6 @@ public BoardDto(Pieces pieces) { } public Map getBoard() { - return board; + return Collections.unmodifiableMap(board); } } \ No newline at end of file diff --git a/src/main/java/wooteco/chess/dto/ChessGameDto.java b/src/main/java/wooteco/chess/dto/ChessGameDto.java index 1cd65b4b68..752f7e79d5 100644 --- a/src/main/java/wooteco/chess/dto/ChessGameDto.java +++ b/src/main/java/wooteco/chess/dto/ChessGameDto.java @@ -5,17 +5,16 @@ public class ChessGameDto { private Long gameId; - private BoardDto boardDto; - private Turn turn; - private ScoreResult score; - private boolean normalStatus; + private final BoardDto boardDto; + private final Turn turn; + private final ScoreResult score; + private final boolean normalStatus; public ChessGameDto(BoardDto boardDto, Turn turn, ScoreResult score, boolean normalStatus) { this.boardDto = boardDto; this.turn = turn; this.score = score; this.normalStatus = normalStatus; - this.gameId = null; // TODO: 2020/04/29 제거할 방법 생각 } public ChessGameDto(Long gameId, BoardDto boardDto, Turn turn, ScoreResult score, boolean normalStatus) { diff --git a/src/main/java/wooteco/chess/dto/DestinationPositionDto.java b/src/main/java/wooteco/chess/dto/DestinationPositionDto.java index c11a65099f..e6e186d038 100644 --- a/src/main/java/wooteco/chess/dto/DestinationPositionDto.java +++ b/src/main/java/wooteco/chess/dto/DestinationPositionDto.java @@ -3,8 +3,8 @@ import wooteco.chess.domain.game.NormalStatus; public class DestinationPositionDto { - private String position; - private NormalStatus normalStatus; + private final String position; + private final NormalStatus normalStatus; public DestinationPositionDto(String position, NormalStatus normalStatus) { this.position = position; diff --git a/src/main/java/wooteco/chess/dto/GamesDto.java b/src/main/java/wooteco/chess/dto/GamesDto.java index f10528a7b7..ac7e64e8b3 100644 --- a/src/main/java/wooteco/chess/dto/GamesDto.java +++ b/src/main/java/wooteco/chess/dto/GamesDto.java @@ -1,16 +1,16 @@ package wooteco.chess.dto; -import java.util.LinkedHashMap; +import java.util.Collections; import java.util.Map; public class GamesDto { - private Map games = new LinkedHashMap<>(); + private final Map games; public GamesDto(Map games) { this.games = games; } public Map getGames() { - return games; + return Collections.unmodifiableMap(games); } } diff --git a/src/main/java/wooteco/chess/dto/MovablePositionsDto.java b/src/main/java/wooteco/chess/dto/MovablePositionsDto.java index 81af3719ee..6fdd7b38a7 100644 --- a/src/main/java/wooteco/chess/dto/MovablePositionsDto.java +++ b/src/main/java/wooteco/chess/dto/MovablePositionsDto.java @@ -1,10 +1,11 @@ package wooteco.chess.dto; +import java.util.Collections; import java.util.List; public class MovablePositionsDto { - private List movablePositionNames; - private String position; + private final List movablePositionNames; + private final String position; public MovablePositionsDto(List movablePositionNames, String position) { this.movablePositionNames = movablePositionNames; @@ -12,7 +13,7 @@ public MovablePositionsDto(List movablePositionNames, String position) { } public List getMovablePositionNames() { - return movablePositionNames; + return Collections.unmodifiableList(movablePositionNames); } public String getPosition() { diff --git a/src/main/java/wooteco/chess/dto/MoveStatusDto.java b/src/main/java/wooteco/chess/dto/MoveStatusDto.java index dd75f33145..21b50a26a6 100644 --- a/src/main/java/wooteco/chess/dto/MoveStatusDto.java +++ b/src/main/java/wooteco/chess/dto/MoveStatusDto.java @@ -5,9 +5,9 @@ public class MoveStatusDto { private static final String EMPTY_STRING = ""; - private boolean normalStatus; - private Color winner; - private String exception; + private final boolean normalStatus; + private final Color winner; + private final String exception; public MoveStatusDto(boolean normalStatus, String exception) { this.normalStatus = normalStatus; diff --git a/src/main/java/wooteco/chess/entity/Game.java b/src/main/java/wooteco/chess/entity/Game.java index 8399700e61..6de7a89a4a 100644 --- a/src/main/java/wooteco/chess/entity/Game.java +++ b/src/main/java/wooteco/chess/entity/Game.java @@ -2,6 +2,7 @@ import org.springframework.data.annotation.Id; +import java.util.Collections; import java.util.HashSet; import java.util.Objects; import java.util.Set; @@ -44,7 +45,7 @@ public Boolean getCanContinue() { } public Set getHistories() { - return histories; + return Collections.unmodifiableSet(histories); } @Override diff --git a/src/main/java/wooteco/chess/service/SparkChessService.java b/src/main/java/wooteco/chess/service/SparkChessService.java index 90db39e6a8..19e73372e9 100644 --- a/src/main/java/wooteco/chess/service/SparkChessService.java +++ b/src/main/java/wooteco/chess/service/SparkChessService.java @@ -22,7 +22,8 @@ public ChessGameDto setBoard() throws SQLException { load(chessGame); - return new ChessGameDto(new BoardDto(chessGame.getPieces()), chessGame.getTurn(), chessGame.calculateScore(), NormalStatus.YES.isNormalStatus()); + return new ChessGameDto(new BoardDto(chessGame.getPieces()), chessGame.getTurn(), chessGame.calculateScore(), + NormalStatus.YES.isNormalStatus()); } private void load(ChessGame chessGame) throws SQLException { @@ -49,7 +50,8 @@ public MoveStatusDto move(MovingPosition movingPosition) throws SQLException { chessGame.move(movingPosition); if (chessGame.isKingDead()) { - MoveStatusDto moveStatusDto = new MoveStatusDto(NormalStatus.YES.isNormalStatus(), chessGame.getAliveKingColor()); + MoveStatusDto moveStatusDto = new MoveStatusDto(NormalStatus.YES.isNormalStatus(), + chessGame.getAliveKingColor()); clearHistory(); return moveStatusDto; } diff --git a/src/main/java/wooteco/chess/service/SpringChessService.java b/src/main/java/wooteco/chess/service/SpringChessService.java deleted file mode 100644 index 9601f18984..0000000000 --- a/src/main/java/wooteco/chess/service/SpringChessService.java +++ /dev/null @@ -1,86 +0,0 @@ -package wooteco.chess.service; - -import org.springframework.stereotype.Service; -import wooteco.chess.dao.FakeHistoryDao; -import wooteco.chess.dao.HistoryDao; -import wooteco.chess.domain.game.ChessGame; -import wooteco.chess.domain.game.NormalStatus; -import wooteco.chess.domain.position.MovingPosition; -import wooteco.chess.dto.BoardDto; -import wooteco.chess.dto.ChessGameDto; -import wooteco.chess.dto.MovablePositionsDto; -import wooteco.chess.dto.MoveStatusDto; - -import java.sql.SQLException; -import java.util.List; - -@Service -public class SpringChessService { - HistoryDao historyDao = new FakeHistoryDao(); - - public void clearHistory() throws SQLException { - historyDao.clear(); - } - - public ChessGameDto setBoard() throws SQLException { - ChessGame chessGame = new ChessGame(); - - load(chessGame); - - return new ChessGameDto(new BoardDto(chessGame.getPieces()), chessGame.getTurn(), chessGame.calculateScore(), NormalStatus.YES.isNormalStatus()); - } - - private void load(ChessGame chessGame) throws SQLException { - List histories = selectAllHistory(); - - for (MovingPosition movingPosition : histories) { - chessGame.move(movingPosition); - } - } - - private List selectAllHistory() throws SQLException { - return historyDao.selectAll(); - } - - public MovablePositionsDto findMovablePositions(String source) throws SQLException { - ChessGame chessGame = new ChessGame(); - load(chessGame); - - List movablePositionNames = chessGame.findMovablePositionNames(source); - - return new MovablePositionsDto(movablePositionNames, source); - - } - - public MoveStatusDto checkMovable(MovingPosition movingPosition) { - try { - ChessGame chessGame = new ChessGame(); - - load(chessGame); - chessGame.move(movingPosition); - return new MoveStatusDto(NormalStatus.YES.isNormalStatus()); - } catch (IllegalArgumentException | UnsupportedOperationException | NullPointerException | SQLException e) { - return new MoveStatusDto(NormalStatus.NO.isNormalStatus(), e.getMessage()); - } - } - - public MoveStatusDto move(MovingPosition movingPosition) throws SQLException { - ChessGame chessGame = new ChessGame(); - load(chessGame); - chessGame.move(movingPosition); - - MoveStatusDto moveStatusDto = new MoveStatusDto(NormalStatus.YES.isNormalStatus()); - - if (chessGame.isKingDead()) { - moveStatusDto = new MoveStatusDto(NormalStatus.YES.isNormalStatus(), chessGame.getAliveKingColor()); - } - - insertHistory(movingPosition); - - return moveStatusDto; - } - - private void insertHistory(MovingPosition movingPosition) throws SQLException { - historyDao.insert(movingPosition); - } -} diff --git a/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java b/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java index 878a90c26c..900cfe6cdb 100644 --- a/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java +++ b/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java @@ -33,7 +33,7 @@ private Long save(String gameName) { public ChessGameDto setBoardBy(Long id) { ChessGame chessGame = new ChessGame(); load(chessGame, id); - return new ChessGameDto(new BoardDto(chessGame.getPieces()), chessGame.getTurn(), + return new ChessGameDto(id, new BoardDto(chessGame.getPieces()), chessGame.getTurn(), chessGame.calculateScore(), NormalStatus.YES.isNormalStatus()); } @@ -61,7 +61,6 @@ public MovablePositionsDto findMovablePositions(Long id, String source) { List movablePositionNames = chessGame.findMovablePositionNames(source); return new MovablePositionsDto(movablePositionNames, source); - } public MoveStatusDto checkMovable(Long id, MovingPosition movingPosition) { diff --git a/src/main/java/wooteco/chess/web/ConnectionManager.java b/src/main/java/wooteco/chess/web/ConnectionManager.java index acbf1d5f13..d028c4471d 100644 --- a/src/main/java/wooteco/chess/web/ConnectionManager.java +++ b/src/main/java/wooteco/chess/web/ConnectionManager.java @@ -23,7 +23,8 @@ public Connection getConnection() { // 드라이버 연결 try { - con = DriverManager.getConnection("jdbc:mysql://" + server + "/" + database + option, userName, password); + con = DriverManager.getConnection("jdbc:mysql://" + server + "/" + database + option, userName, + password); System.out.println("정상적으로 연결되었습니다."); } catch (SQLException e) { System.err.println("연결 오류:" + e.getMessage()); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index a21076509d..2ed3c334a4 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -4,5 +4,4 @@ spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:13306/chess?useSSL=fa spring.datasource.username=root spring.datasource.password=root logging.level.org.springframework.jdbc=TRACE -# 제이슨의 도움으로 해결 spring.datasource.initialization-mode=ALWAYS From 22c8587280d956b98be490347c3a058de17a67cd Mon Sep 17 00:00:00 2001 From: toneyparky Date: Mon, 4 May 2020 16:24:17 +0900 Subject: [PATCH 22/22] =?UTF-8?q?fix:=20=EC=82=AC=EC=9A=A9=EC=9E=90?= =?UTF-8?q?=EA=B0=80=20=EB=8D=B0=EC=9D=B4=ED=84=B0=EB=B2=A0=EC=9D=B4?= =?UTF-8?q?=EC=8A=A4=EC=97=90=20=EC=A0=80=EC=9E=A5=EB=90=98=EC=96=B4=20?= =?UTF-8?q?=EC=9E=88=EC=A7=80=20=EC=95=8A=EC=9D=80=20=EA=B2=8C=EC=9E=84=20?= =?UTF-8?q?=EC=95=84=EC=9D=B4=EB=94=94=EB=A1=9C=20=EC=A0=95=EB=B3=B4?= =?UTF-8?q?=EB=A5=BC=20=EC=A0=84=EB=8B=AC=ED=95=A0=20=EB=95=8C=20=EC=98=88?= =?UTF-8?q?=EC=99=B8=20=EC=B2=98=EB=A6=AC=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC?= =?UTF-8?q?=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SpringChessController 예외 정보를 담은 Dto 생성해 반환 SpringDataJDBCChessService 예외 발생 시 예외 전달 --- .../chess/controller/SpringChessController.java | 9 +++++++-- .../chess/service/SpringDataJDBCChessService.java | 10 +++++++--- src/main/resources/static/public/js/chess.js | 7 ++++--- src/main/resources/static/public/js/index.js | 1 - 4 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/main/java/wooteco/chess/controller/SpringChessController.java b/src/main/java/wooteco/chess/controller/SpringChessController.java index 1cd7040d36..3b7d4593cf 100644 --- a/src/main/java/wooteco/chess/controller/SpringChessController.java +++ b/src/main/java/wooteco/chess/controller/SpringChessController.java @@ -94,8 +94,13 @@ public String checkMovable(@PathVariable Long id, @RequestParam String startPosi @PostMapping("/board/{id}") @ResponseBody public String saveHistory(@PathVariable Long id, @RequestBody MovingPosition movingPosition) { - MoveStatusDto moveStatusDto = springDataJDBCChessService.move(id, movingPosition); - return JsonTransformer.toJson(moveStatusDto); + try { + MoveStatusDto moveStatusDto = springDataJDBCChessService.move(id, movingPosition); + return JsonTransformer.toJson(moveStatusDto); + } catch (IllegalArgumentException e) { + MoveStatusDto moveStatusDto = new MoveStatusDto(false, e.getMessage()); + return JsonTransformer.toJson(moveStatusDto); + } } @GetMapping("/loading/{id}") diff --git a/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java b/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java index 900cfe6cdb..14fb3fa6ea 100644 --- a/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java +++ b/src/main/java/wooteco/chess/service/SpringDataJDBCChessService.java @@ -75,7 +75,7 @@ public MoveStatusDto checkMovable(Long id, MovingPosition movingPosition) { } } - public MoveStatusDto move(Long id, MovingPosition movingPosition) { + public MoveStatusDto move(Long id, MovingPosition movingPosition) throws IllegalArgumentException { ChessGame chessGame = new ChessGame(); load(chessGame, id); chessGame.move(movingPosition); @@ -93,12 +93,16 @@ public MoveStatusDto move(Long id, MovingPosition movingPosition) { } private void updateCanContinueToFalse(Long id) { - Game game = gameRepository.findById(id).get(); // TODO: 2020/05/01 예외 처리 수정 + Game game = gameRepository.findById(id) + .orElseThrow(() -> + new IllegalArgumentException("해당 id의 방이 없습니다.")); gameRepository.save(new Game(game.getId(), game.getName(), false)); } private void insertHistory(Long id, MovingPosition movingPosition) { - Game game = gameRepository.findById(id).get(); // TODO: 2020/05/01 예외 처리 생각하기 + Game game = gameRepository.findById(id) + .orElseThrow(() -> + new IllegalArgumentException("해당 id의 방이 없습니다.")); History history = new History(movingPosition.getStart(), movingPosition.getEnd()); game.addHistory(history); gameRepository.save(game); diff --git a/src/main/resources/static/public/js/chess.js b/src/main/resources/static/public/js/chess.js index 9510e0167e..c3bfe2cf72 100644 --- a/src/main/resources/static/public/js/chess.js +++ b/src/main/resources/static/public/js/chess.js @@ -55,7 +55,6 @@ window.onload = function () { (async function () { const chessGame = await getChessGame(); const board = await chessGame["boardDto"]["board"]; - console.log(board); const turn = chessGame["turn"]; const score = chessGame["score"]["scores"]; @@ -74,7 +73,6 @@ window.onload = function () { .then(res => res.json()) .then(data => { startPosition = data.position; - console.log(data.normalStatus); if (data.normalStatus === false) { alert(data.exception); startPosition = null; @@ -122,7 +120,10 @@ window.onload = function () { return winnerResponse.json(); }) .then(winnerData => { - console.log(winnerData); + if (!winnerData["normalStatus"]) { + alert(winnerData["exception"]); + return location.href = "/"; + } if (winnerData["winner"] !== "NONE") { let winnerTeam = winnerData["winner"]; return location.href = `/result/${winnerTeam}`; diff --git a/src/main/resources/static/public/js/index.js b/src/main/resources/static/public/js/index.js index 600da704b1..15a690fe2c 100644 --- a/src/main/resources/static/public/js/index.js +++ b/src/main/resources/static/public/js/index.js @@ -16,7 +16,6 @@ window.onload = function () { return await response.json(); }) .then(data => { - console.log(data); let gameId = data["gameId"]; window.location.href = `/game/${gameId}`; });