diff --git a/README2.md b/README2.md deleted file mode 100644 index 6eddf2821e..0000000000 --- a/README2.md +++ /dev/null @@ -1,32 +0,0 @@ -- [ ] 숫자는 1~9까지다. -- [ ] 서로 다른수 3자리 숫자 이여야한다. -- [ ] 게임 룰 - - [ ] 같은 수가 같은 자리에 있으면 스트라이크 - - [ ] 다른 자리에 있으면 볼 - - [ ] 전혀 없으면 낫싱 -- [ ] 컴퓨터는 서로 다른 3개의 숫자를 랜덤으로 받아온다. -- [ ] 3개의 숫자를 모두 맞추면 게임이 종료된다. -- [ ] 게임이 종료 됐을경우 다시 시작하거나 완전히 종료할 수 있다. - - [ ] 재시작은 1, 종료는 2 -- [ ] 사용자가 잘못된 값을 입력할 경우 IllegalArgumentException 발생시키고 종료된다. -- [ ] 출력 시 볼은 스트라이크 앞에 있어야 한다. - - - - -Computer 클래스는 오직 컴퓨터 번호를 랜덤으로 가져오는 역할 => 인터페이스로 Generate??? 만들어도 될듯 -PlayerNumber 클래스는 오직 플레이어의 번호를 저장하는 역할 -Computer, PlayerNumber은 GameResult 클래스에서 스트라이크와 볼의 개수를 달라고 함. -GameResult에서 받은 값을 OutputView에서 다시 받아 출력. => 바로 OutputView로 해도 될듯 -만약 3스트라이크가 나오면 {3스트라이크 출력문}을 출력하고, 다시할건지 끝낼건지 InputView 에서 숫자 입력. -Retry클래스는 InputView에서 값을 받아 오직 시작할건지 끝낼건지 판단하는 역할. -만약 1을 입력했을때, 첫 시작 메세지를 제외하고 다시 시작. -그럼 Game클래스는 무엇일까... 전반적인 게임 플레이 담당? 흐름 제어..? - - -Game 클래스에서 Computer, PlayerNumber 클래스 한테 숫자를 달라는 메세지 요청 => InputView말고 각자의 클래스에서 만드는게 나아보임. -두개의 숫자를 받고 그 결과를 판단해 달라고 GameResult에 요청(판단만) => 그 결과 값을 OutputView에 요청 -그러다 3스트라이크가 나오면 InputView에 요청해서 retry 숫자 요청. -전달 받고 1이면 첫 시작 문구 제외 다시 시작... - -각자 Computer, PlayerNumber, Retry에는 값을 자기가 가지고 있어야함. 그 값을 가지고 요청 diff --git a/docs/README.md b/docs/README.md index e69de29bb2..0bc944f84c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -0,0 +1,13 @@ +### 기능 목록 정리 +- [x] 컴퓨터의 숫자를 랜덤으로 가져온다. +- [x] 사용자의 숫자를 입력한다. + - [x] 입력이 3자리가 아니면 예외가 발생한다. + - [x] 입력이 숫자 형식이 아니면 예외가 발생한다. + - [x] 빈 값이 입력되면 예외가 발생한다. +- [x] 컴퓨터의 숫자와 사용자의 숫자를 비교한다. +- [x] 결과를 출력한다. + - [x] 같은 수가 같은 자리에 있으면 스트라이크, 다른 자리에 있으면 볼, 같은 수가 전혀 없으면 낫싱 + - [x] 3스트라이크가 나왔을 시, 성공 문구를 출력한다. +- [x] 재시작 여부를 입력한다. + - [x] 1또는 2가 입력되지 않으면 예외가 발생한다. + \ No newline at end of file diff --git a/src/main/java/baseball/Application.java b/src/main/java/baseball/Application.java index 1ab01ec011..7fa9cec6ed 100644 --- a/src/main/java/baseball/Application.java +++ b/src/main/java/baseball/Application.java @@ -1,11 +1,13 @@ package baseball; -import baseball.controller.Game; +import baseball.controller.BaseballGame; +import baseball.domain.RandomNumberGenerator; +import baseball.service.BaseballService; public class Application { - - public static void main(String[] args) { - Game game = new Game(); - game.play(); - } + public static void main(String[] args) { + BaseballGame baseballGame = new BaseballGame(new RandomNumberGenerator(), + new BaseballService()); + baseballGame.start(); + } } diff --git a/src/main/java/baseball/constants/Constants.java b/src/main/java/baseball/constants/Constants.java deleted file mode 100644 index 30ced4bfb8..0000000000 --- a/src/main/java/baseball/constants/Constants.java +++ /dev/null @@ -1,9 +0,0 @@ -package baseball.constants; - -public class Constants { - - public static final int MAX_SIZE = 3; - public static final int successStrikeNum = 3; - public static final int MIN_VALUE = 1; - public static final int MAX_VALUE = 9; -} diff --git a/src/main/java/baseball/controller/BaseballGame.java b/src/main/java/baseball/controller/BaseballGame.java new file mode 100644 index 0000000000..092274545f --- /dev/null +++ b/src/main/java/baseball/controller/BaseballGame.java @@ -0,0 +1,83 @@ +package baseball.controller; + +import baseball.domain.CompareResult; +import baseball.domain.Computer; +import baseball.domain.Player; +import baseball.domain.RandomNumberGenerator; +import baseball.domain.Retry; +import baseball.service.BaseballService; +import baseball.view.InputView; +import baseball.view.OutputView; +import java.util.Arrays; +import java.util.stream.Collectors; + +public class BaseballGame { + + private static final String ALL_STRIKE = "3스트라이크"; + + private final RandomNumberGenerator randomNumberGenerator; + private final BaseballService baseballService; + + public BaseballGame(RandomNumberGenerator randomNumberGenerator, + BaseballService baseballService) { + this.randomNumberGenerator = randomNumberGenerator; + this.baseballService = baseballService; + } + + public void start() { + OutputView.printStart(); + playGame(); + } + + private void playGame() { + while (true) { + Computer computerNumber = generateComputerNumber(); + calculateNumber(computerNumber); + Retry retry = selectRetryCommand(); + if (isEnd(retry)) { + break; + } + } + } + + private void calculateNumber(Computer computerNumber) { + while (true) { + Player playerNumber = generatePlayerNumber(); + CompareResult compareResult = baseballService.compare(computerNumber, playerNumber); + OutputView.printResult(compareResult); + if (isResultAllStrike(compareResult)) { + OutputView.endMessage(); + break; + } + } + } + + private boolean isResultAllStrike(CompareResult compareResult) { + return compareResult.toString().equals(ALL_STRIKE); + } + + private boolean isEnd(Retry retry) { + return retry == Retry.STOP; + } + + private Computer generateComputerNumber() { + return randomNumberGenerator.generate(); + } + + private Player generatePlayerNumber() { + OutputView.printMessage(); + String playerNumber = InputView.readPlayerNumber(); + return new Player(Arrays.stream(playerNumber.split("")) + .map(Integer::parseInt) + .collect(Collectors.toList())); + } + + private Retry selectRetryCommand() { + OutputView.restartMessage(); + String retryCommand = InputView.readRestartCommand(); + return Arrays.stream(Retry.values()) + .filter(retry -> retry.getCommand() == Integer.parseInt(retryCommand)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("1 또는 2를 입력해야 합니다.")); + } +} diff --git a/src/main/java/baseball/controller/Game.java b/src/main/java/baseball/controller/Game.java deleted file mode 100644 index 7dd8771e82..0000000000 --- a/src/main/java/baseball/controller/Game.java +++ /dev/null @@ -1,58 +0,0 @@ -package baseball.controller; - -import baseball.constants.Constants; -import baseball.domain.Judge; -import baseball.domain.Retry; -import baseball.domain.Computer; -import baseball.domain.PlayerNumber; -import baseball.view.GameResult; -import baseball.view.InputView; - -public class Game { - - InputView inputView = new InputView(); - GameResult gameResult = new GameResult(); - - public void play() { - inputView.gameStartMessage(); - boolean restart = true; - while (restart) { - startGame(inputView.generateSuccessNumber()); - restart = tryRetry(); - } - } - - private void startGame(Computer computer) { - while (true) { - inputView.printInputMessage(); - PlayerNumber inputPlayerNumber = inputView.inputPlayerNumber(); - Judge judge = judge(computer, inputPlayerNumber); - gameResult.printResult(judge.getStrikeCount(), judge.getBallCount()); - if (judge.getStrikeCount() == Constants.successStrikeNum) { - break; - } - } - } - - public Judge judge(Computer computer, PlayerNumber playerNumber) { - int strikeCount = 0; - int ballCount = 0; - for (int i = 0; i < Constants.MAX_SIZE; i++) { - if (computer.getComputerNumber().get(i).equals(playerNumber.getPlayerNumber().get(i))) { - strikeCount++; - } - if (computer.getComputerNumber().contains(playerNumber.getPlayerNumber().get(i))) { - ballCount++; - } - } - ballCount -= strikeCount; - return new Judge(strikeCount, ballCount); - } - - private boolean tryRetry() { - String retryNumber = inputView.inputRetryNumber(); - Retry retry = new Retry(retryNumber); - return retry.isRetry(); - } -} - diff --git a/src/main/java/baseball/domain/CompareResult.java b/src/main/java/baseball/domain/CompareResult.java new file mode 100644 index 0000000000..8e340b60e5 --- /dev/null +++ b/src/main/java/baseball/domain/CompareResult.java @@ -0,0 +1,39 @@ +package baseball.domain; + +public class CompareResult { + + private static final String NOTHING_TEXT = "낫싱"; + private static final String BALL_TEXT = "볼"; + private static final String STRIKE_TEXT = "스트라이크"; + + private final CountOfBalls count; + + public CompareResult(CountOfBalls count) { + this.count = count; + } + + @Override + public String toString() { + int ballCount = count.getBallCount(); + int strikeCount = count.getStrikeCount(); + ballCount -= strikeCount; + + if (count.isNothing()) { + return NOTHING_TEXT; + } + if (count.isStrikeCountZero()) { + return String.format("%d%s", ballCount, BALL_TEXT); + } + if (count.isBallCountZero()) { + return String.format("%d%s", strikeCount, STRIKE_TEXT); + } + if (count.isThreeStrike()) { + return String.format("%d%s", strikeCount, STRIKE_TEXT); + } + return String.format("%d%s %d%s", ballCount, BALL_TEXT, strikeCount, STRIKE_TEXT); + } + + public CountOfBalls getCountOfBalls() { + return count; + } +} diff --git a/src/main/java/baseball/domain/Computer.java b/src/main/java/baseball/domain/Computer.java index 4a795d7d5e..5a6e5cd13d 100644 --- a/src/main/java/baseball/domain/Computer.java +++ b/src/main/java/baseball/domain/Computer.java @@ -4,14 +4,17 @@ public class Computer { - private final List computerNumber; + private final List computerNumber; - public Computer(List computerNumber) { - this.computerNumber = computerNumber; - } + public Computer(List computerNumber) { + this.computerNumber = computerNumber; + } - public List getComputerNumber() { - return computerNumber; - } -} + public int getComputerNumberByIndex(int index) { + return computerNumber.get(index); + } + public boolean isComputerNumberContainsPlayerNumber(Integer playerNumber) { + return computerNumber.contains(playerNumber); + } +} diff --git a/src/main/java/baseball/domain/CountOfBalls.java b/src/main/java/baseball/domain/CountOfBalls.java new file mode 100644 index 0000000000..006fe9972b --- /dev/null +++ b/src/main/java/baseball/domain/CountOfBalls.java @@ -0,0 +1,39 @@ +package baseball.domain; + +public class CountOfBalls { + + private int strikeCount; + private int ballCount; + + public int getStrikeCount() { + return strikeCount; + } + + public int getBallCount() { + return ballCount; + } + + public void increaseBallCount() { + ballCount++; + } + + public void increaseStrikeCount() { + strikeCount++; + } + + public boolean isStrikeCountZero() { + return strikeCount == 0; + } + + public boolean isBallCountZero() { + return ballCount == 0; + } + + public boolean isThreeStrike() { + return strikeCount == 3; + } + + public boolean isNothing() { + return isBallCountZero() && isStrikeCountZero(); + } +} diff --git a/src/main/java/baseball/domain/Judge.java b/src/main/java/baseball/domain/Judge.java deleted file mode 100644 index bfe46f4345..0000000000 --- a/src/main/java/baseball/domain/Judge.java +++ /dev/null @@ -1,20 +0,0 @@ -package baseball.domain; - -public class Judge { - - private final int strikeCount; - private final int ballCount; - - public Judge(int strikeCount, int ballCount) { - this.strikeCount = strikeCount; - this.ballCount = ballCount; - } - - public int getBallCount() { - return ballCount; - } - - public int getStrikeCount() { - return strikeCount; - } -} diff --git a/src/main/java/baseball/domain/NumberGenerator.java b/src/main/java/baseball/domain/NumberGenerator.java new file mode 100644 index 0000000000..e0672a5677 --- /dev/null +++ b/src/main/java/baseball/domain/NumberGenerator.java @@ -0,0 +1,6 @@ +package baseball.domain; + +public interface NumberGenerator { + + Computer generate(); +} diff --git a/src/main/java/baseball/domain/Player.java b/src/main/java/baseball/domain/Player.java new file mode 100644 index 0000000000..b5b5ed1a0b --- /dev/null +++ b/src/main/java/baseball/domain/Player.java @@ -0,0 +1,27 @@ +package baseball.domain; + +import java.util.List; + +public class Player { + + private final List playerNumber; + + public Player(List playerNumber) { + validatePlayerNumber(playerNumber); + this.playerNumber = playerNumber; + } + + private void validatePlayerNumber(List playerNumber) { + validateSize(playerNumber); + } + + private void validateSize(List playerNumber) { + if(playerNumber.size() != 3){ + throw new IllegalArgumentException("3자리를 입력 해야 합니다."); + } + } + + public int getPlayerNumberByIndex(int index) { + return playerNumber.get(index); + } +} diff --git a/src/main/java/baseball/domain/PlayerNumber.java b/src/main/java/baseball/domain/PlayerNumber.java deleted file mode 100644 index 3de0f36556..0000000000 --- a/src/main/java/baseball/domain/PlayerNumber.java +++ /dev/null @@ -1,44 +0,0 @@ -package baseball.domain; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import baseball.constants.Constants; - -public class PlayerNumber { - - private final List playerNumber; - - public PlayerNumber(List playerNumber) { - this.playerNumber = playerNumber; - } - - private void duplicatePlayerNumber(List playerNumber) throws IllegalArgumentException { - Set numberSet = new HashSet<>(); - for (int num : playerNumber) { - if (!numberSet.add(num)) { - throw new IllegalArgumentException("입력된 숫자는 중복될 수 없습니다."); - } - } - } - - private void validateInputNumbers(List playerNumbers) throws IllegalArgumentException { - for (Integer num : playerNumbers) { - String numStr = num.toString(); - if (!numStr.matches("^[1-9]$")) { - throw new IllegalArgumentException("입력된 숫자는 1이상 9이하의 숫자만 가능합니다."); - } - } - } - - private void checkNumberSize(List playerNumber) throws IllegalArgumentException { - if (playerNumber.size() != Constants.MAX_SIZE) { - throw new IllegalArgumentException("입력된 숫자는 3자리 이어야 합니다."); - } - } - - public List getPlayerNumber() { - return playerNumber; - } -} \ No newline at end of file diff --git a/src/main/java/baseball/domain/RandomNumberGenerator.java b/src/main/java/baseball/domain/RandomNumberGenerator.java new file mode 100644 index 0000000000..362f3b4c07 --- /dev/null +++ b/src/main/java/baseball/domain/RandomNumberGenerator.java @@ -0,0 +1,29 @@ +package baseball.domain; + +import camp.nextstep.edu.missionutils.Randoms; +import java.util.ArrayList; +import java.util.List; + +public class RandomNumberGenerator implements NumberGenerator { + + private static final int MIN_NUMBER = 1; + private static final int MAX_NUMBER = 9; + private static final int MAX_SIZE = 3; + + @Override + public Computer generate() { + List computerNumbers = new ArrayList<>(); + while (computerNumbers.size() < MAX_SIZE) { + int randomNumber = generateRandomNumber(); + if (!computerNumbers.contains(randomNumber)) { + computerNumbers.add(randomNumber); + } + } + computerNumbers.forEach(System.out::println); + return new Computer(computerNumbers); + } + + private int generateRandomNumber() { + return Randoms.pickNumberInRange(MIN_NUMBER, MAX_NUMBER); + } +} diff --git a/src/main/java/baseball/domain/Retry.java b/src/main/java/baseball/domain/Retry.java index bdb217f58b..636060f8f6 100644 --- a/src/main/java/baseball/domain/Retry.java +++ b/src/main/java/baseball/domain/Retry.java @@ -1,44 +1,16 @@ package baseball.domain; -public class Retry { +public enum Retry { + RETRY(1), + STOP(2); - private final boolean retryNumber; + private final int command; - public Retry(String retryNumber){ - checkException(retryNumber); - this.retryNumber = conversionRetryNumber(retryNumber); - } + Retry(int command) { + this.command = command; + } - public void checkException(String retryNumber) { - checkRetryNumberSize(retryNumber); - validateInputRetryNumbers(retryNumber); - checkInputNumber(retryNumber); - } - - public void validateInputRetryNumbers(String retryNumber) throws IllegalArgumentException { - if (retryNumber.matches("^[a-zA-Z]$")) { - throw new IllegalArgumentException("입력된 값은 숫자가 아닙니다."); - } - } - - public void checkRetryNumberSize(String retryNumber) throws IllegalArgumentException { - if(retryNumber.length() != 1){ - throw new IllegalArgumentException("입력은 한글자만 가능합니다."); - } - } - - private void checkInputNumber(String retryNumber) throws IllegalArgumentException { - int retry = Integer.parseInt(retryNumber); - if (retry < 1 || retry > 2) { - throw new IllegalArgumentException("입력된 숫자는 1 또는 2 이어야 합니다."); - } - } - - public boolean conversionRetryNumber(String retryNumber){ - return retryNumber.equals("1"); - } - - public boolean isRetry() { - return retryNumber; - } + public int getCommand() { + return command; + } } diff --git a/src/main/java/baseball/service/BaseballService.java b/src/main/java/baseball/service/BaseballService.java new file mode 100644 index 0000000000..3a046bd84f --- /dev/null +++ b/src/main/java/baseball/service/BaseballService.java @@ -0,0 +1,34 @@ +package baseball.service; + +import baseball.domain.CompareResult; +import baseball.domain.Computer; +import baseball.domain.CountOfBalls; +import baseball.domain.Player; + +public class BaseballService { + + private static final int MAX_SIZE = 3; + + public CompareResult compare(Computer computer, Player player) { + CountOfBalls countOfBalls = new CountOfBalls(); + calculateStrikeCount(computer,player,countOfBalls); + calculateBallCount(computer,player,countOfBalls); + return new CompareResult(countOfBalls); + } + + private void calculateStrikeCount(Computer computer, Player player, CountOfBalls countOfBalls) { + for (int i = 0; i < MAX_SIZE; i++) { + if (computer.getComputerNumberByIndex(i) == player.getPlayerNumberByIndex(i)) { + countOfBalls.increaseStrikeCount(); + } + } + } + + private void calculateBallCount(Computer computer, Player player, CountOfBalls countOfBalls) { + for (int i = 0; i < MAX_SIZE; i++) { + if (computer.isComputerNumberContainsPlayerNumber(player.getPlayerNumberByIndex(i))) { + countOfBalls.increaseBallCount(); + } + } + } +} diff --git a/src/main/java/baseball/view/GameResult.java b/src/main/java/baseball/view/GameResult.java deleted file mode 100644 index 3925fa1c85..0000000000 --- a/src/main/java/baseball/view/GameResult.java +++ /dev/null @@ -1,33 +0,0 @@ -package baseball.view; - -public class GameResult { - - public void printResult(int strikeCount, int ballCount) { - if (strikeCount == 3) { - System.out.println("3스트라이크"); - endMessage(); - restartMessage(); - } - if (strikeCount == 0 && ballCount >= 1) { - System.out.println(ballCount + "볼"); - } - if (strikeCount >= 1 && ballCount == 0 && strikeCount < 3) { - System.out.println(strikeCount + "스트라이크"); - } - if (strikeCount == 0 && ballCount == 0) { - System.out.println("낫싱"); - } - if (strikeCount >= 1 && ballCount >= 1) { - System.out.println(ballCount + "볼 " + strikeCount + "스트라이크"); - } - } - - public void endMessage() { - System.out.println("3개의 숫자를 모두 맞히셨습니다! 게임 종료"); - } - - public void restartMessage() { - System.out.println("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요."); - } - -} diff --git a/src/main/java/baseball/view/InputView.java b/src/main/java/baseball/view/InputView.java index 29342eafd3..4ab70e88ea 100644 --- a/src/main/java/baseball/view/InputView.java +++ b/src/main/java/baseball/view/InputView.java @@ -1,47 +1,40 @@ package baseball.view; -import java.util.ArrayList; -import java.util.List; - -import baseball.constants.Constants; -import baseball.domain.Computer; -import baseball.domain.PlayerNumber; import camp.nextstep.edu.missionutils.Console; -import camp.nextstep.edu.missionutils.Randoms; public class InputView { - public Computer generateSuccessNumber() { - List computerNumber = new ArrayList<>(); - while (computerNumber.size() < 3) { - int randomNumber = Randoms.pickNumberInRange(Constants.MIN_VALUE, Constants.MAX_VALUE); - if (!computerNumber.contains(randomNumber)) - computerNumber.add(randomNumber); - } - for (Integer computerNumber1 : computerNumber) { - System.out.println(computerNumber1); - } - return new Computer(computerNumber); - } - - public PlayerNumber inputPlayerNumber() { - List playerNumber = new ArrayList<>(); - String number = Console.readLine(); - for (int i = 0; i < number.length(); i++) { - playerNumber.add(number.charAt(i) - '0'); - } - return new PlayerNumber(playerNumber); - } - - public String inputRetryNumber() { - return Console.readLine(); - } - - public void gameStartMessage(){ - System.out.println("숫자 야구 게임을 시작합니다."); - } - - public void printInputMessage(){ - System.out.print("숫자를 입력해 주세요 : "); - } -} \ No newline at end of file + private InputView() { + } + + public static String readPlayerNumber() { + String playerNumber = Console.readLine(); + validateInputs(playerNumber); + return playerNumber; + } + + public static String readRestartCommand() { + String command = Console.readLine(); + validateInputs(command); + return command; + } + + private static void validateInputs(String inputs) { + validateBlank(inputs); + validateInteger(inputs); + } + + private static void validateBlank(String inputs) { + if (inputs.isBlank()) { + throw new IllegalArgumentException("올바르지 않은 입력입니다."); + } + } + + private static Integer validateInteger(String inputs) { + try { + return Integer.valueOf(inputs); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("숫자를 입력해야 합니다."); + } + } +} diff --git a/src/main/java/baseball/view/OutputView.java b/src/main/java/baseball/view/OutputView.java new file mode 100644 index 0000000000..e76106e81f --- /dev/null +++ b/src/main/java/baseball/view/OutputView.java @@ -0,0 +1,30 @@ +package baseball.view; + +import baseball.domain.CompareResult; + +public class OutputView { + + private OutputView() { + } + + public static void printStart() { + System.out.println("숫자 야구 게임을 시작합니다."); + } + + public static void printMessage() { + System.out.print("숫자를 입력해주세요 : "); + } + + public static void printResult(CompareResult compareResult) { + System.out.println(compareResult); + } + + public static void endMessage() { + System.out.println("3개의 숫자를 모두 맞히셨습니다! 게임 종료"); + } + + public static void restartMessage() { + System.out.println("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요."); + } + +} diff --git a/src/test/java/baseball/GameResultTest.java b/src/test/java/baseball/GameResultTest.java deleted file mode 100644 index 187ae9c22b..0000000000 --- a/src/test/java/baseball/GameResultTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package baseball; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - - -import org.junit.jupiter.api.Test; - -import baseball.view.GameResult; - -class GameResultTest { - - @Test - void printResult_3Strikes() { - GameResult gameResult = new GameResult(); - - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - PrintStream originalOutput = System.out; - System.setOut(new PrintStream(outputStream)); - - gameResult.printResult(3, 0); - - System.setOut(originalOutput); - String capturedOutput = outputStream.toString().trim(); - - String expectedOutput = "3스트라이크\n3개의 숫자를 모두 맞히셨습니다! 게임 종료\n게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요."; - - assertThat(capturedOutput).isEqualTo(expectedOutput); - } - - @Test - void printResult_0Strike_0Ball() { - GameResult gameResult = new GameResult(); - - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - PrintStream originalOutput = System.out; - System.setOut(new PrintStream(outputStream)); - - gameResult.printResult(0,0); - - System.setOut(originalOutput); - String capturedOutput = outputStream.toString().trim(); - - String expectedOutput = "낫싱"; - - assertThat(capturedOutput).isEqualTo(expectedOutput); - } - - @Test - void printResult_2Strike_1Ball() { - GameResult gameResult = new GameResult(); - - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - PrintStream originalOutput = System.out; - System.setOut(new PrintStream(outputStream)); - - gameResult.printResult(2,1); - - System.setOut(originalOutput); - String capturedOutput = outputStream.toString().trim(); - - String expectedOutput = "1볼 2스트라이크"; // 볼 먼저 출력 - - assertThat(capturedOutput).isEqualTo(expectedOutput); - } - - @Test - void printResult_0Strike_2Ball() { - GameResult gameResult = new GameResult(); - - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - PrintStream originalOutput = System.out; - System.setOut(new PrintStream(outputStream)); - - gameResult.printResult(0,2); - - System.setOut(originalOutput); - String capturedOutput = outputStream.toString().trim(); - - String expectedOutput = "2볼"; - - assertThat(capturedOutput).isEqualTo(expectedOutput); - } - - @Test - void printResult_2Strike_0Ball() { - GameResult gameResult = new GameResult(); - - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - PrintStream originalOutput = System.out; - System.setOut(new PrintStream(outputStream)); - - gameResult.printResult(2,0); - - System.setOut(originalOutput); - String capturedOutput = outputStream.toString().trim(); - - String expectedOutput = "2스트라이크"; - - assertThat(capturedOutput).isEqualTo(expectedOutput); - } - -} \ No newline at end of file diff --git a/src/test/java/baseball/GameTest.java b/src/test/java/baseball/GameTest.java deleted file mode 100644 index 5522ec819a..0000000000 --- a/src/test/java/baseball/GameTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package baseball; - -import static org.assertj.core.api.AssertionsForInterfaceTypes.*; - -import java.util.List; - -import org.junit.jupiter.api.Test; - -import baseball.controller.Game; -import baseball.domain.Computer; -import baseball.domain.Judge; -import baseball.domain.PlayerNumber; - -class GameTest { - - @Test - void judge_3Strike() { - //given - - Computer computer = new Computer(List.of(1, 2, 3)); - PlayerNumber playerNumber = new PlayerNumber(List.of(1, 2, 3)); - Game game = new Game(); - - //when - Judge result = game.judge(computer, playerNumber); - - //then - assertThat(result.getStrikeCount()).isEqualTo(3); // 예상되는 스트라이크 개수 입력 - assertThat(result.getBallCount()).isEqualTo(0); // 예상되는 볼 개수 입력 - } - - @Test - void judge_1Strike_2Ball() { - //given - Computer computer = new Computer(List.of(1, 2, 3)); - PlayerNumber playerNumber = new PlayerNumber(List.of(1, 3, 2)); - Game game = new Game(); - - //when - Judge result = game.judge(computer, playerNumber); - - //then - assertThat(result.getStrikeCount()).isEqualTo(1); // 예상되는 스트라이크 개수 입력 - assertThat(result.getBallCount()).isEqualTo(2); // 예상되는 볼 개수 입력 - } - - @Test - void judge_0Strike_2Ball() { - //given - Computer computer = new Computer(List.of(1, 2, 3)); - PlayerNumber playerNumber = new PlayerNumber(List.of(2, 1, 4)); - Game game = new Game(); - - //when - Judge result = game.judge(computer, playerNumber); - - //then - assertThat(result.getStrikeCount()).isEqualTo(0); // 예상되는 스트라이크 개수 입력 - assertThat(result.getBallCount()).isEqualTo(2); // 예상되는 볼 개수 입력 - } - - @Test - void judge_0Strike_0Ball() { - //given - Computer computer = new Computer(List.of(1, 2, 3)); - PlayerNumber playerNumber = new PlayerNumber(List.of(4, 5, 6)); - Game game = new Game(); - - //when - Judge result = game.judge(computer, playerNumber); - - //then - assertThat(result.getStrikeCount()).isEqualTo(0); // 예상되는 스트라이크 개수 입력 - assertThat(result.getBallCount()).isEqualTo(0); // 예상되는 볼 개수 입력 - } -} \ No newline at end of file diff --git a/src/test/java/baseball/PlayerNumberTest.java b/src/test/java/baseball/PlayerNumberTest.java deleted file mode 100644 index d8dba427da..0000000000 --- a/src/test/java/baseball/PlayerNumberTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package baseball; - -import camp.nextstep.edu.missionutils.test.NsTest; -import org.junit.jupiter.api.Test; - - -import static camp.nextstep.edu.missionutils.test.Assertions.assertSimpleTest; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -class PlayerNumberTest extends NsTest{ - - @Test - void 플레이어_입력_중복_테스트() { - assertSimpleTest(() -> - assertThatThrownBy(() -> runException("122")) - .isInstanceOf(IllegalArgumentException.class) - ); - } - - @Test - void 플레이어_입력_영어_테스트() { - assertSimpleTest(() -> - assertThatThrownBy(() -> runException("11a")) - .isInstanceOf(IllegalArgumentException.class) - ); - } - - @Test - void 플레이어_입력_범위_테스트() { - assertSimpleTest(() -> - assertThatThrownBy(() -> runException("012")) - .isInstanceOf(IllegalArgumentException.class) - ); - } - - @Override - public void runMain() { - Application.main(new String[]{}); - } - -} \ No newline at end of file diff --git a/src/test/java/baseball/RetryTest.java b/src/test/java/baseball/RetryTest.java deleted file mode 100644 index d59c7f9985..0000000000 --- a/src/test/java/baseball/RetryTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package baseball; - - - -import static org.assertj.core.api.AssertionsForInterfaceTypes.*; - -import org.junit.jupiter.api.Test; - -import baseball.domain.Retry; - -class RetryTest { - - @Test - void retry_1_2_테스트() { - //given <= 이렇게 주어졌을때 - - //when <= 이걸 실행하면 - - //then <= 이렇게 나와야해 - assertThatThrownBy(() -> new Retry("3")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("입력된 숫자는 1 또는 2 이어야 합니다."); - } - - @Test - void retry_영어_입력_테스트() { - //given <= 이렇게 주어졌을때 - - //when <= 이걸 실행하면 - - //then <= 이렇게 나와야해 - assertThatThrownBy(() -> new Retry("e")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("입력된 값은 숫자가 아닙니다."); - } - - @Test - void retry_입력_사이즈_테스트() { - //given <= 이렇게 주어졌을때 - - //when <= 이걸 실행하면 - - //then <= 이렇게 나와야해 - assertThatThrownBy(() -> new Retry("12")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("입력은 한글자만 가능합니다."); - } -} \ No newline at end of file diff --git a/src/test/java/baseball/domain/CompareResultTest.java b/src/test/java/baseball/domain/CompareResultTest.java new file mode 100644 index 0000000000..5e4e0fc88b --- /dev/null +++ b/src/test/java/baseball/domain/CompareResultTest.java @@ -0,0 +1,52 @@ +package baseball.domain; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@DisplayName("CompareResult") +public class CompareResultTest { + + @Test + void 스트라이크_횟수가_0개고_볼_횟수가_0이면_낫싱을_반환한다() { + CountOfBalls count = new CountOfBalls(); + + CompareResult result = new CompareResult(count); + + assertEquals("낫싱", result.toString()); + } + + @Test + void 스트라이크_횟수가_1개고_볼_횟수가_0이면_1스트라이크를_반환한다() { + CountOfBalls count = new CountOfBalls(); + + count.increaseStrikeCount(); + + CompareResult result = new CompareResult(count); + assertEquals("1스트라이크", result.toString()); + } + + @Test + public void 스트라이크_횟수가_0개고_볼_횟수가_1이면_1볼을_반환한다() { + CountOfBalls count = new CountOfBalls(); + + count.increaseBallCount(); + + CompareResult result = new CompareResult(count); + assertEquals("1볼", result.toString()); + } + + + @Test + public void 스트라이크_횟수가_3개고_볼_횟수가_0이면_3스트라이크를_반환한다() { + CountOfBalls count = new CountOfBalls(); + + count.increaseStrikeCount(); + count.increaseStrikeCount(); + count.increaseStrikeCount(); + + CompareResult result = new CompareResult(count); + assertEquals("3스트라이크", result.toString()); + } +} diff --git a/src/test/java/baseball/domain/ComputerTest.java b/src/test/java/baseball/domain/ComputerTest.java new file mode 100644 index 0000000000..93598b2531 --- /dev/null +++ b/src/test/java/baseball/domain/ComputerTest.java @@ -0,0 +1,26 @@ +package baseball.domain; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +@DisplayName("Computer") +class ComputerTest { + + @Test + void getComputerNumberByIndex_메서드는_인덱스의_값을_가져온다() { + Computer computer = new Computer(List.of(1,5,6)); + + assertThat(computer.getComputerNumberByIndex(2)).isEqualTo(6); + } + + @Test + void isComputerNumberContainsPlayerNumber_메서드는_PlayerNumber이_포함되어_있는지_확인한다() { + Computer computer = new Computer(List.of(1,5,6)); + Integer playerNumber = 5; + + assertThat(computer.isComputerNumberContainsPlayerNumber(playerNumber)).isTrue(); + } +} \ No newline at end of file diff --git a/src/test/java/baseball/domain/CountOfBallsTest.java b/src/test/java/baseball/domain/CountOfBallsTest.java new file mode 100644 index 0000000000..1e9053e1b2 --- /dev/null +++ b/src/test/java/baseball/domain/CountOfBallsTest.java @@ -0,0 +1,46 @@ +package baseball.domain; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@DisplayName("CountOfBalls") +public class CountOfBallsTest { + + @Test + void increaseBallCount_메서드는_볼_횟수를_1_증가시킨다() { + CountOfBalls count = new CountOfBalls(); + + count.increaseBallCount(); + + assertEquals(1, count.getBallCount()); + } + + @Test + void increaseStrikeCount_메서드는_스트라이크_횟수를_1_증가시킨다() { + CountOfBalls count = new CountOfBalls(); + + count.increaseStrikeCount(); + + assertEquals(1, count.getStrikeCount()); + } + + @Test + void isThreeStrike_메서드는_스트라이크_카운트가_3일때_true를_반환한다() { + CountOfBalls count = new CountOfBalls(); + + count.increaseStrikeCount(); + count.increaseStrikeCount(); + count.increaseStrikeCount(); + + assertTrue(count.isThreeStrike()); + } + + @Test + void isNothing_메서드는_볼_횟수와_스트라이크_횟수가_0이면_true를_반환한다() { + CountOfBalls count = new CountOfBalls(); + + assertTrue(count.isNothing()); + } +} diff --git a/src/test/java/baseball/domain/PlayerTest.java b/src/test/java/baseball/domain/PlayerTest.java new file mode 100644 index 0000000000..0aa0b6644a --- /dev/null +++ b/src/test/java/baseball/domain/PlayerTest.java @@ -0,0 +1,18 @@ +package baseball.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.*; + +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +@DisplayName("Player") +class PlayerTest { + + @Test + void 생성자는_올바르지_않은_사이즈를_입력시_IllegalArgumentException_발생시킨다() { + assertThatThrownBy(() -> new Player(List.of(1, 2))).isInstanceOf( + IllegalArgumentException.class); + } +} \ No newline at end of file diff --git a/src/test/java/baseball/service/BaseballServiceTest.java b/src/test/java/baseball/service/BaseballServiceTest.java new file mode 100644 index 0000000000..40ecf77eab --- /dev/null +++ b/src/test/java/baseball/service/BaseballServiceTest.java @@ -0,0 +1,27 @@ +package baseball.service; + +import static org.junit.jupiter.api.Assertions.*; + +import baseball.domain.CompareResult; +import baseball.domain.Computer; +import baseball.domain.CountOfBalls; +import baseball.domain.Player; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +@DisplayName("BaseballService") +class BaseballServiceTest { + + @Test + void compare_메서드는_스트라이크_개수와_볼_개수를_계산한다() { + Computer computer = new Computer(List.of(1, 2, 3)); + Player player = new Player(List.of(1, 2, 3)); + + // 테스트 실행 + BaseballService baseballService = new BaseballService(); + CompareResult result = baseballService.compare(computer, player); + + assertEquals(3, result.getCountOfBalls().getStrikeCount()); + } +} \ No newline at end of file