-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathGameManager.java
More file actions
89 lines (78 loc) · 2.68 KB
/
GameManager.java
File metadata and controls
89 lines (78 loc) · 2.68 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package domain;
import domain.board.Board;
import domain.board.BoardFactory;
import domain.board.Formation;
import domain.board.FormationCommand;
import domain.player.Name;
import domain.player.Players;
import java.util.List;
import java.util.function.Supplier;
import view.InputParser;
import view.InputView;
import view.OutputView;
public class GameManager {
private final InputView inputView;
private final OutputView outputView;
public GameManager(InputView inputView, OutputView outputView) {
this.inputView = inputView;
this.outputView = outputView;
}
public void play() {
Game game = initializeGame();
outputView.printBoard(game.getBoard());
while (!game.isOver()) {
playTurn(game);
}
outputView.printWinner(game.getWinner());
}
private Game initializeGame() {
Name choName = getPlayerName(Side.CHO);
Players players = retry(() -> {
Name hanName = getPlayerName(Side.HAN);
return Players.createInitial(choName, hanName);
});
Board board = BoardFactory.create(getFormation(Side.CHO), getFormation(Side.HAN));
return new Game(board, players);
}
private Name getPlayerName(Side side) {
return retry(() -> InputParser.parseName(inputView.readPlayerName(side)));
}
private Formation getFormation(Side side) {
return retry(() -> Formation.from(FormationCommand.from(inputView.readFormation(side))));
}
private void playTurn(Game game) {
Position source = selectPiecePosition(game);
retry(() -> {
Position target = InputParser.parsePosition(inputView.readTargetPosition());
game.move(source, target);
});
outputView.printBoard(game.getBoard());
}
private Position selectPiecePosition(Game game) {
return retry(() -> {
Position position = InputParser.parsePosition(inputView.readSourcePosition(game.getCurrentSide()));
List<Position> destinations = game.selectSource(position).getPositions();
outputView.printDestinations(destinations);
return position;
});
}
private <T> T retry(Supplier<T> supplier) {
while (true) {
try {
return supplier.get();
} catch (IllegalArgumentException e) {
outputView.printError(e.getMessage());
}
}
}
private void retry(Runnable action) {
while (true) {
try {
action.run();
return;
} catch (IllegalArgumentException e) {
outputView.printError(e.getMessage());
}
}
}
}