Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[라빈] - 체스 스프링 실습 레벨 1 제출합니다 #30

Merged
merged 6 commits into from
Apr 23, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
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'
testImplementation 'io.rest-assured:rest-assured:3.3.0'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
Expand Down
19 changes: 6 additions & 13 deletions src/main/java/wooteco/chess/SparkChessApplication.java
Original file line number Diff line number Diff line change
@@ -1,22 +1,15 @@
package wooteco.chess;

import spark.ModelAndView;
import spark.template.handlebars.HandlebarsTemplateEngine;
import wooteco.chess.controller.SparkChessController;

import java.util.HashMap;
import java.util.Map;

import static spark.Spark.get;
import static spark.Spark.staticFiles;

public class SparkChessApplication {
public static void main(String[] args) {
get("/", (req, res) -> {
Map<String, Object> model = new HashMap<>();
return render(model, "index.hbs");
});
}
staticFiles.location("/templates/public");

SparkChessController sparkChessController = new SparkChessController();

private static String render(Map<String, Object> model, String templatePath) {
return new HandlebarsTemplateEngine().render(new ModelAndView(model, templatePath));
sparkChessController.route();
}
}
6 changes: 3 additions & 3 deletions src/main/java/wooteco/chess/SpringChessApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
@SpringBootApplication
public class SpringChessApplication {

public static void main(String[] args) {
SpringApplication.run(SpringChessApplication.class, args);
}
public static void main(String[] args) {
SpringApplication.run(SpringChessApplication.class, args);
}

}
122 changes: 122 additions & 0 deletions src/main/java/wooteco/chess/controller/SparkChessController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package wooteco.chess.controller;

import spark.ModelAndView;
import spark.Request;
import spark.Response;
import spark.template.handlebars.HandlebarsTemplateEngine;
import wooteco.chess.domain.game.NormalStatus;
import wooteco.chess.domain.piece.Color;
import wooteco.chess.domain.position.MovingPosition;
import wooteco.chess.dto.DestinationPositionDto;
import wooteco.chess.dto.MovablePositionsDto;
import wooteco.chess.dto.MoveStatusDto;
import wooteco.chess.service.ChessWebService;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import static spark.Spark.get;
import static spark.Spark.post;
import static wooteco.chess.web.JsonTransformer.json;

public class SparkChessController {
private ChessWebService chessWebService;

public SparkChessController() {
this.chessWebService = new ChessWebService();
}

public void route() {
get("/", this::index);

get("/new", this::startNewGame);

get("/loading", this::loadGame);

get("/board", (req, res) -> chessWebService.setBoard(), json());

post("/board", this::postBoard);

post("/source", this::getMovablePositions, json());

post("/destination", this::move, json());
}

private String index(Request req, Response res) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

메서드의 컨벤션은 동사라는 피드백을 받은 적이 있습니다. 변경해보는 것은 어떨까요?

Map<String, Object> model = new HashMap<>();
model.put("normalStatus", NormalStatus.YES.isNormalStatus());

return render(model, "index.html");
}

private String startNewGame(Request req, Response res) throws SQLException {
Map<String, Object> model = new HashMap<>();
model.put("normalStatus", NormalStatus.YES.isNormalStatus());

chessWebService.clearHistory();

return render(model, "chess.html");
}

private String loadGame(Request req, Response res) {
Map<String, Object> model = new HashMap<>();
model.put("normalStatus", NormalStatus.YES.isNormalStatus());

return render(model, "chess.html");
}

private String postBoard(Request req, Response res) {
Map<String, Object> model = new HashMap<>();

try {
MoveStatusDto moveStatusDto = chessWebService.move(new MovingPosition(req.queryParams("source"), req.queryParams("destination")));

model.put("normalStatus", moveStatusDto.getNormalStatus());
model.put("winner", moveStatusDto.getWinner());

if (moveStatusDto.getWinner().isNone()) {
return render(model, "chess.html");
}
return render(model, "result.html");
} catch (IllegalArgumentException | UnsupportedOperationException | NullPointerException | SQLException e) {
model.put("normalStatus", NormalStatus.NO.isNormalStatus());
model.put("exception", e.getMessage());
model.put("winner", Color.NONE);
return render(model, "chess.html");
}
}

private Map<String, Object> getMovablePositions(Request req, Response res) throws SQLException {
Map<String, Object> model = new HashMap<>();
try {
MovablePositionsDto movablePositionsDto = chessWebService.findMovablePositions(req.queryParams("source"));

model.put("movable", movablePositionsDto.getMovablePositionNames());
model.put("position", movablePositionsDto.getPosition());
model.put("normalStatus", NormalStatus.YES.isNormalStatus());

return model;
} catch (IllegalArgumentException | UnsupportedOperationException | NullPointerException e) {
model.put("normalStatus", NormalStatus.NO.isNormalStatus());
model.put("exception", e.getMessage());

return model;
}
}

private Map<String, Object> move(Request req, Response res) {
Map<String, Object> model = new HashMap<>();

DestinationPositionDto destinationPositionDto = chessWebService.chooseDestinationPosition(req.queryParams("destination"));

model.put("normalStatus", destinationPositionDto.getNormalStatus().isNormalStatus());
model.put("position", destinationPositionDto.getPosition());

return model;
}

private static String render(Map<String, Object> model, String templatePath) {
return new HandlebarsTemplateEngine().render(new ModelAndView(model, templatePath));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class ChessController {
public class SpringChessController {
@GetMapping("/")
public String index() {
return "index";
Expand Down
35 changes: 35 additions & 0 deletions src/main/java/wooteco/chess/dao/FakeHistoryDao.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package wooteco.chess.dao;

import wooteco.chess.domain.position.MovingPosition;

import java.util.LinkedHashMap;
import java.util.Map;

public class FakeHistoryDao {
private final Map<Integer, MovingPosition> fakeHistoryDao;

public FakeHistoryDao() {
fakeHistoryDao = new LinkedHashMap<>();

fakeHistoryDao.put(1, new MovingPosition("a2", "a4"));
fakeHistoryDao.put(2, new MovingPosition("a7", "a6"));
fakeHistoryDao.put(3, new MovingPosition("a4", "a5"));
fakeHistoryDao.put(4, new MovingPosition("b7", "b5"));
}

public Map<Integer, MovingPosition> selectAll() {
return fakeHistoryDao;
}

public void clear() {
fakeHistoryDao.clear();
}

public void insert(String start, String end) {
insert(new MovingPosition(start, end));
}

public void insert(MovingPosition movingPosition) {
fakeHistoryDao.put(fakeHistoryDao.size() + 1, movingPosition);
}
}
43 changes: 43 additions & 0 deletions src/main/java/wooteco/chess/dao/HistoryDao.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package wooteco.chess.dao;

import wooteco.chess.domain.position.MovingPosition;
import wooteco.chess.web.ConnectionManager;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HistoryDao {
private final ConnectionManager connectionManager = new ConnectionManager();

public void insert(MovingPosition movingPosition) throws SQLException {
String query = "INSERT INTO history (start, end) VALUES (?, ?)";
try (PreparedStatement pstmt = connectionManager.getConnection().prepareStatement(query)) {
pstmt.setString(1, movingPosition.getStart());
pstmt.setString(2, movingPosition.getEnd());
pstmt.executeUpdate();
}
}

public List<MovingPosition> selectAll() throws SQLException {
String query = "SELECT * FROM history";
try (PreparedStatement pstmt = connectionManager.getConnection().prepareStatement(query); ResultSet rs = pstmt.executeQuery()) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

; 뒤에서 줄바꿈이 이루어지면 가독성이 좋아지지 않을까요?


List<MovingPosition> result = new ArrayList<>();
while (rs.next()) {
result.add(new MovingPosition(rs.getString("start"), rs.getString("end")));
}
return Collections.unmodifiableList(result);
}
}

public void clear() throws SQLException {
String query = "DELETE FROM history";
try (PreparedStatement pstmt = connectionManager.getConnection().prepareStatement(query)) {
pstmt.executeUpdate();
}
}
}
61 changes: 61 additions & 0 deletions src/main/java/wooteco/chess/domain/game/ChessGame.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package wooteco.chess.domain.game;

import wooteco.chess.domain.piece.Color;
import wooteco.chess.domain.piece.Piece;
import wooteco.chess.domain.piece.pieces.Pieces;
import wooteco.chess.domain.piece.pieces.PiecesInitializer;
import wooteco.chess.domain.position.MovingPosition;
import wooteco.chess.domain.position.Position;
import wooteco.chess.domain.position.PositionFactory;
import wooteco.chess.domain.position.positions.Positions;

import java.util.List;
import java.util.stream.Collectors;

public class ChessGame {
private Pieces pieces;
private Turn turn;

public ChessGame() {
pieces = PiecesInitializer.operate();
turn = new Turn(Color.WHITE);
}

public void move(MovingPosition movingPosition) {
pieces.move(movingPosition.getStartPosition(), movingPosition.getEndPosition(), turn.getColor());
turn = turn.change();
}

public ScoreResult calculateScore() {
return new ScoreResult(pieces);
}

public boolean isKingDead() {
return pieces.isKingDead();
}

public Color getAliveKingColor() {
return pieces.getAliveKingColor();
}

public Positions findMovablePositions(Position position) {
Piece piece = pieces.findBy(position, turn.getColor());
return piece.createMovablePositions(pieces.getPieces());
}

public List<String> findMovablePositionNames(String position) {
return this.findMovablePositions(PositionFactory.of(position))
.getPositions()
.stream()
.map(Position::toString)
.collect(Collectors.toList());
}

public Turn getTurn() {
return turn;
}

public Pieces getPieces() {
return pieces;
}
}
16 changes: 16 additions & 0 deletions src/main/java/wooteco/chess/domain/game/NormalStatus.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package wooteco.chess.domain.game;

public enum NormalStatus {
YES(true),
NO(false);

private boolean normalStatus;

NormalStatus(boolean normalStatus) {
this.normalStatus = normalStatus;
}

public boolean isNormalStatus() {
return normalStatus;
}
}
Loading