Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[숫자 야구 게임] 이은지 미션 제출합니다. #604

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,23 @@
## 📝 License

This project is [MIT](https://github.com/woowacourse/java-baseball-precourse/blob/master/LICENSE) licensed.

## 구현할 기능 목록
Computer
- 3자리 난수 생성

Player
- 사용자 3자리수 숫자 input
- 게임 재시작 여부 input

CompareNumber
- 사용자 숫자 입력 후 정답과 비교
- 힌트 출력
- 3 Strike인 경우 게임 종료

Game
- 게임 실행
- 게임 재시작 및 종료

InputException
- 예외 관리(플레이어가 세자리 숫자를 입력하지 않은 경우, 동일한 숫자를 입력한 경우, 1~9 범위 외 숫자를 입력하는 경우, 게임 종료 시 1 또는 2를 입력하지 않았을 경우)
3 changes: 2 additions & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#Sun Aug 25 23:56:59 KST 2024
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
8 changes: 7 additions & 1 deletion src/main/java/baseball/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

public class Application {
public static void main(String[] args) {
//TODO: 숫자 야구 게임 구현
try {
Game game = new Game();
game.play();
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
System.exit(1); // 프로그램 종료
}
}
}
59 changes: 59 additions & 0 deletions src/main/java/baseball/CompareNumber.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package baseball;

import java.util.List;

public class CompareNumber {
private boolean gameOver;

public void compareNumber(Player player, Computer computer) {
List<Integer> randomNumber = computer.getRandomNumber();
player.playerInputNumber(); // 숫자 입력
List<Integer> playerNumber = player.getInputNumber();
Comment on lines +9 to +11

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

다른 곳에서 숫자를 만들고 매개변수로 넘겨주는건 어떨까요?


int strike = calculateStrikes(randomNumber, playerNumber);
int ball = calculateBalls(randomNumber, playerNumber);

// 결과 출력
if (strike == 0 && ball == 0) {
System.out.println("낫싱");
} else {
System.out.println(ball + "볼 " + strike + "스트라이크");
}

// 3 스트라이크인 경우 게임 종료
if (strike == 3) {
printGameOverMessage();
gameOver = true;
} else {
gameOver = false;
}
Comment on lines +17 to +29

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

숫자 비교하는 메서드랑 분리하는게 좋을 것 같아요

}

private int calculateStrikes(List<Integer> randomNumber, List<Integer> playerNumber) {
int strike = 0;
for (int i = 0; i < randomNumber.size(); i++) {
if (randomNumber.get(i).equals(playerNumber.get(i))) {
strike++;
}
}
return strike;
}

private int calculateBalls(List<Integer> randomNumber, List<Integer> playerNumber) {
int ball = 0;
for (int i = 0; i < randomNumber.size(); i++) {
if (randomNumber.contains(playerNumber.get(i)) && !randomNumber.get(i).equals(playerNumber.get(i))) {
ball++;
}
}
return ball;
}

public boolean isGameOver() {
return gameOver;
}

private void printGameOverMessage() {
System.out.println("3개의 숫자를 모두 맞히셨습니다! 게임 종료");
}
}
46 changes: 46 additions & 0 deletions src/main/java/baseball/Computer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package baseball;

import camp.nextstep.edu.missionutils.Randoms;

import java.util.ArrayList;
import java.util.List;

public class Computer {
private List<Integer> randomNumber;

public Computer() {
this.randomNumber = generateRandomNumber();
}

private List<Integer> generateRandomNumber() {
List<Integer> numbers = new ArrayList<>();
boolean isDuplicate;

do {
isDuplicate = false;
for (int i = 0; i < 3; i++) {
int num = Randoms.pickNumberInRange(1, 9); // 1 ~ 9 난수 생성
if (!numbers.contains(num)) {
numbers.add(num);
} else {
isDuplicate = true;
break; // 중복이 발생하면 break -> 다시 시도
}
}

if (isDuplicate) {
numbers.clear();
}
} while (isDuplicate || numbers.size() < 3);
Comment on lines +19 to +34

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

depth가 너무 깊은것 같아요 분리해줘요


return numbers;
}

public List<Integer> getRandomNumber() {
return this.randomNumber;
}

public void resetRandomNumber() {
this.randomNumber = generateRandomNumber();
}
Comment on lines +43 to +45

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

generateNewRandomNumber() 는 어때요

}
38 changes: 38 additions & 0 deletions src/main/java/baseball/Game.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package baseball;

public class Game {
private final Computer computer;
private final Player player;
private final CompareNumber compareNumber;

public Game() {
computer = new Computer();
player = new Player();
compareNumber = new CompareNumber();
}

public void play() {
boolean continuePlaying = true;

while (continuePlaying) {
compareNumber.compareNumber(player, computer);

if (compareNumber.isGameOver()) {
System.out.println("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.");
String replayInput = player.inputReplay();

if ("1".equals(replayInput)) {
// 게임 재시작
computer.resetRandomNumber(); // 새로운 난수 생성
} else if ("2".equals(replayInput)) {
// 게임 종료
continuePlaying = false;
} else {
// 잘못된 입력 처리
System.out.println("잘못된 입력입니다. 게임을 종료합니다.");
continuePlaying = false;
}
}
}
}
Comment on lines +14 to +37

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

한 메서드안에 너무 많은게 들어가있는것 같아요
분리해줘요

}
56 changes: 56 additions & 0 deletions src/main/java/baseball/InputException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package baseball;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

public class InputException {
private static final String NOT_NUMBER = "숫자가 아닙니다.";

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

static final 을 붙이면 무슨일이 일어날까요

private static final String NOT_NUMBER_LENGTH = "숫자의 길이가 맞지 않습니다.";
private static final String DUPLICATE = "중복된 숫자가 있습니다.";
private static final String OUT_OF_RANGE = "숫자가 1~9 범위를 벗어났습니다.";
private static final String NUMBER_REGEX = "^[0-9]*$";

private InputException() {
}

public static void validatesNumber(String inputNumbers) {
isNumber(inputNumbers);
isLength(inputNumbers);
isDuplicate(inputNumbers);
isInRange(inputNumbers);
}

public static void isNumber(String inputNumbers) {
if (!Pattern.matches(NUMBER_REGEX, inputNumbers)) {
exception(NOT_NUMBER);
}
}

public static void isLength(String inputNumbers) {
if (inputNumbers.length() != 3) {
exception(NOT_NUMBER_LENGTH);
}
}

public static void isDuplicate(String inputNumbers) {
List<String> inputNumberList = Arrays.asList(inputNumbers.split(""));
if (inputNumberList.stream().distinct().count() < 3) {
exception(DUPLICATE);
}
}

public static void isInRange(String inputNumbers) {
List<String> inputNumberList = Arrays.asList(inputNumbers.split(""));
for (String num : inputNumberList) {
int number = Integer.parseInt(num);
if (number < 1 || number > 9) {
exception(OUT_OF_RANGE);
}
}
}

private static void exception(String message) {
throw new IllegalArgumentException(message);
}
}
36 changes: 36 additions & 0 deletions src/main/java/baseball/Player.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package baseball;

import camp.nextstep.edu.missionutils.Console;
import java.util.ArrayList;
import java.util.List;

import static baseball.InputException.validatesNumber;

public class Player {
private final List<Integer> inputNumber;

public Player() {
this.inputNumber = new ArrayList<>();
}
Comment on lines +12 to +14

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

생성자에서 이걸 해주는 이유가 궁금해요


public void playerInputNumber() { // 사용자 입력 메서드
System.out.println("숫자를 입력해주세요 : ");
String input = Console.readLine();
validatesNumber(input);

inputNumber.clear(); // 이전 입력값 지우기
for (char ch : input.toCharArray()) { // 입력받은 숫자를 리스트에 저장
inputNumber.add(Character.getNumericValue(ch));
}
}

public List<Integer> getInputNumber(){
return this.inputNumber;
}

// 게임 재시작 여부
public String inputReplay(){
String inputReplay = Console.readLine();
return inputReplay;
}
Comment on lines +32 to +35

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이걸 Player 클래스에서 받는 이유가 궁금해요

}