-
Notifications
You must be signed in to change notification settings - Fork 461
Expand file tree
/
Copy pathBoard.java
More file actions
56 lines (46 loc) · 1.94 KB
/
Board.java
File metadata and controls
56 lines (46 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package chess;
import chess.piece.Knight;
import chess.piece.Piece;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class Board {
private final Map<Position, Piece> pieces;
public Board(Map<Position, Piece> pieces) {
this.pieces = pieces;
}
public void move(Position departure, Position arrival) {
Piece piece = pieces.get(departure);
List<Position> canMovePositions = piece.calculateCanMovePosition(departure, arrival);
if (!piece.isSameType(new Knight(Color.WHITE))) {
Optional<Position> isAlreadyExistAnotherPiece = canMovePositions.stream()
.filter(position -> !position.equals(arrival)) // 도착지 탐색 제외
.filter(position -> pieces.get(position) != null)
.findAny();
if (isAlreadyExistAnotherPiece.isPresent()) {
throw new IllegalArgumentException("해당 위치로는 이동할 수 없습니다.");
}
}
// 해당 위치에 아무것도 존재하지 않는다면 이동한다
if (pieces.get(arrival) == null) {
pieces.put(arrival, piece);
pieces.remove(departure);
return;
}
Piece currentPieceOfArrivalPosition = pieces.get(arrival);
// 같은 팀 일 경우 해당 위치로 이동할 수 없다.
if (piece.getColor() == currentPieceOfArrivalPosition.getColor()) {
throw new IllegalArgumentException("해당 위치로는 이동할 수 없습니다.");
}
// 해당 위치의 기물을 제거 후 이동한다.
pieces.remove(arrival);
pieces.put(arrival, piece);
pieces.remove(departure);
}
public Optional<Piece> getPieceOfOptional(Column column, Row row) {
return Optional.ofNullable(pieces.get(new Position(column, row)));
}
public Piece getPiece(Position position) {
return pieces.get(position);
}
}