-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathBaseballGame.java
More file actions
72 lines (59 loc) · 1.95 KB
/
BaseballGame.java
File metadata and controls
72 lines (59 loc) · 1.95 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
package baseball.controller;
import baseball.exception.CommonErrorCode;
import baseball.exception.InvalidInputException;
import lombok.RequiredArgsConstructor;
import baseball.model.ComputerNumber;
import baseball.model.Judge;
import baseball.model.Result;
import baseball.model.UserGuess;
import baseball.view.InputView;
import baseball.view.OutputView;
import java.util.function.Supplier;
@RequiredArgsConstructor
public class BaseballGame {
private final InputView inputView;
private final OutputView outputView;
private final Supplier<ComputerNumber> computerNumberSupplier;
public void run() {
while (true) {
playSingleGame();
if (!askRestart()) {
return;
}
}
}
private void playSingleGame() {
ComputerNumber targetNum = computerNumberSupplier.get();
outputView.printStartMessage();
while (true) {
try {
String raw = inputView.readGuess();
UserGuess guess = UserGuess.from(raw);
Result result = Judge.judge(targetNum, guess);
outputView.printHint(result);
if (result.isThreeStrike()) {
outputView.printGameEndMessage();
break;
}
} catch (InvalidInputException e) {
outputView.printError(e.getMessage());
}
}
}
private boolean askRestart() {
while (true) {
try {
String cmd = inputView.readRestartCommand();
validateRestartCommand(cmd);
return "1".equals(cmd);
} catch (InvalidInputException e) {
outputView.printError(e.getMessage());
}
}
}
private void validateRestartCommand(String cmd) {
if (!"1".equals(cmd) && !"2".equals(cmd)) {
throw new InvalidInputException(CommonErrorCode.INVALID_COMMAND);
}
}
}