-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathGameController.java
More file actions
96 lines (82 loc) · 2.09 KB
/
GameController.java
File metadata and controls
96 lines (82 loc) · 2.09 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
90
91
92
93
94
95
96
package baseball.controller;
import java.util.ArrayList;
import java.util.List;
import baseball.model.CompareResult;
import baseball.model.Game;
import baseball.view.InputView;
import baseball.view.OutputView;
public class GameController {
private final Game game;
private final InputView inputView;
private final OutputView outputView;
public GameController(Game game, InputView inputView, OutputView outputView) {
this.game = game;
this.inputView = inputView;
this.outputView = outputView;
}
public void play() {
while (true) {
playSingleGame();
if (shouldExit()) {
return;
}
game.reset();
}
}
private void playSingleGame() {
while (true) {
if (guess()) {
outputView.printGameEnd(game.getDigitsLength());
return;
}
}
}
private boolean guess() {
try {
CompareResult result = compareInput();
outputView.printResult(result);
return isGameEnd(result);
} catch (RuntimeException exception) {
outputView.printError(exception.getMessage());
}
return false;
}
private CompareResult compareInput() {
String input = inputView.readDigits();
List<Integer> digits = parseDigits(input);
return game.compare(digits);
}
private List<Integer> parseDigits(String input) {
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < input.length(); i++) {
char digit = input.charAt(i);
validateDigit(digit);
numbers.add(digit - '0');
}
return numbers;
}
private void validateDigit(char digit) {
if (digit < '0' || digit > '9') {
throw new RuntimeException("숫자만 입력해 주세요");
}
}
private boolean isGameEnd(CompareResult result) {
return result.strike() == result.length();
}
private boolean shouldExit() {
while (true) {
try {
int command = inputView.readGameCommand();
validateGameCommand(command);
return command == 2;
} catch (RuntimeException exception) {
outputView.printError(exception.getMessage());
}
}
}
private void validateGameCommand(int command) {
if (command != 1 && command != 2) {
throw new RuntimeException("1 또는 2를 입력해 주세요.");
}
}
}