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

20221130 자동차경주게임 #510

Open
wants to merge 26 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
19154aa
docs: 기능 구현 목록 작성
SEUNGHEE96 Nov 28, 2022
c62613d
feat: 자동차 이름과 횟수 입력 받는 기능 구현
SEUNGHEE96 Nov 28, 2022
e410a87
feat: 게임 작동 기능 구현
SEUNGHEE96 Nov 28, 2022
d50cb77
fix: 자바 버전 수정
SEUNGHEE96 Nov 29, 2022
8216e04
feat: Car 객체 기능 구현
SEUNGHEE96 Nov 29, 2022
7781a1b
refactor: inputView 메소드 수정
SEUNGHEE96 Nov 29, 2022
6c1a7dc
feat: 경주 결과 출력 기능 구현
SEUNGHEE96 Nov 29, 2022
831879f
feat: 자동차 경주 게임 기능 구현
SEUNGHEE96 Nov 29, 2022
5330643
feat: 자동차 객체 저장 기능 구현
SEUNGHEE96 Nov 29, 2022
5eebd7b
feat: 각 라운드 결과 저장 기능
SEUNGHEE96 Nov 29, 2022
7948334
refactor: 라운드 출력 기능 수정
SEUNGHEE96 Nov 29, 2022
b7639da
feat: 우승자 점수 저장 기능
SEUNGHEE96 Nov 29, 2022
4278019
feat: 우승자 결과 출력 기능 구현
SEUNGHEE96 Nov 29, 2022
ae11c02
refactor: 메소드 분리
SEUNGHEE96 Nov 29, 2022
6e35310
refactor: 메세지 변수 처리
SEUNGHEE96 Nov 29, 2022
69ad5bd
refactor: 변수 변경
SEUNGHEE96 Nov 29, 2022
59906ef
refactor: 우승자 출력문 if-else문 삭제
SEUNGHEE96 Nov 29, 2022
f0bc97a
refactor: 코드 정렬
SEUNGHEE96 Nov 29, 2022
2b0a986
feat: 자동차 이름 예외 처리
SEUNGHEE96 Nov 30, 2022
e2f5b87
feat: 예외 문구 처리
SEUNGHEE96 Nov 30, 2022
6bf1cc3
docs: 기능 구현 목록 완료 체크
SEUNGHEE96 Nov 30, 2022
3a40325
docs: 예외 처리 케이스 추가
SEUNGHEE96 Nov 30, 2022
5a97e9c
feat: 이름 중복 예외 처리
SEUNGHEE96 Nov 30, 2022
8d14910
feat: 시도 횟수 문자 예외 처리
SEUNGHEE96 Nov 30, 2022
1a06be6
docs: 예외처리 기능 구현 완료
SEUNGHEE96 Nov 30, 2022
660be9c
feat: 기능 완성
SEUNGHEE96 Nov 30, 2022
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
5 changes: 5 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,17 @@ dependencies {
implementation('com.github.woowacourse-projects:mission-utils:1.0.0')
}

/*
java {
toolchain {
languageVersion = JavaLanguageVersion.of(8)
}
}
*/


test {
useJUnitPlatform()
}
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
52 changes: 52 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
## 미션 - 자동차 경주 게임

### 개요📌
자동차 이름을 입력 받고, 시도한 횟수 만큼 랜덤으로 전진 또는 멈추는 게임이다.
게임을 완료한 후 우승자를 출력한다.

- - -

### 동작 방식📌

**[게임]**
- 경주할 자동차 이름을 쉼표 기준으로 입력한다.
- 시도할 횟수를 입력한다.
- 각 차수별 실행 결과를 출력한다.
- 0~9까지 랜덤한 숫자를 발행 후, 4 이상의 숫자만 전진한다.
- 우승자를 출력한다.
- 공동 우승자의 경우 쉼표를 기준으로 함께 출력한다.

- - -

### 기능 구현 목록📌

**[게임]**
- [x] 입력한 시도 횟수 만큼 0~9사이의 랜덤 숫자를 발행한다.
- [x] 숫자가 4 이상이면 전진, 아니면 멈춘다.

**[입력]**
- [x] 경주할 자동차 이름을 입력한다.
- [x] 자동차 이름은 쉼표(,)를 기준으로 구분하며 이름은 5자 이하만 가능하다.
- [x] 사용자는 몇 번의 이동을 할 것인지를 입력할 수 있어야 한다.

**[출력]**
- [x] 매 라운드 각 자동차가 얼만큼 전진했는지 출력한다.
- [x] 자동차 경주 게임을 완료한 후 누가 우승했는지를 알려준다.
- [x] 우승자가 여러 명일 경우 쉼표(,)를 이용하여 구분한다.

- - -

### 예외처리📌

**[자동차 입력]**
- [x] 자동차 이름은 5글자를 넘으면 안된다.
- [x] 자동차 이름은 중복되면 안된다.

**[라운드 입력]**
- [x] 숫자가 아닌 문자를 입력하면 안된다.

- - -

### 테스트 케이스📌

- 어떻게 추가해야 할 지 모르겠어서 추가를 하지 못했습니다... ㅠㅠ
6 changes: 5 additions & 1 deletion src/main/java/racingcar/Application.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package racingcar;

import racingcar.controller.racingController;

public class Application {
private static final racingController racingcontroller = new racingController();

public static void main(String[] args) {
// TODO 구현 진행
racingcontroller.start();
}
}
12 changes: 0 additions & 12 deletions src/main/java/racingcar/Car.java

This file was deleted.

34 changes: 34 additions & 0 deletions src/main/java/racingcar/controller/racingController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package racingcar.controller;

import racingcar.message.outputMessage;
import racingcar.model.Car;
import racingcar.model.racingGame;
import racingcar.model.winningResult;
import racingcar.view.inputView;
import racingcar.view.outputView;

import java.util.List;

public class racingController {
Copy link

Choose a reason for hiding this comment

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

클래스의 명명 규칙은 변수와 달리 맨 앞 글자를 대문자로 해줘야 해요!

Copy link
Author

Choose a reason for hiding this comment

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

아! 알려주셔서 감사합니다! 컨벤션 참고해서 수정하도록 하겠습니다 @_@

private final racingGame racinggame = new racingGame();
private final winningResult winningresult = new winningResult();
private final inputView inputView = new inputView();
private final outputView outputview = new outputView();

public void start() {
String[] names = inputView.getNames();
int round = inputView.getRound();
List<Car> cars = racinggame.saveCars(names);
roundResult(round, cars);
winningresult.winningScore(cars);
outputview.result(cars, winningresult.winningScore);
}

private void roundResult(int round, List<Car> cars) {
System.out.println(outputMessage.GAME_ROUND);
for (int i = 0; i < round; i++) {
racinggame.updatePhase(cars);
outputview.round(cars);
}
}
}
8 changes: 8 additions & 0 deletions src/main/java/racingcar/message/exceptionMessage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package racingcar.message;

public class exceptionMessage {
public static final String CAR_NAME_RANGE = "[ERROR] 이름은 다섯 글자를 넘길 수 없습니다.";
public static final String SAME_NAME = "[ERROR] 자동차 이름이 중복되었습니다.";
public static final String ROUND_STIRNG = "[ERROR] 시도 횟수는 숫자여야 합니다.";

}
8 changes: 8 additions & 0 deletions src/main/java/racingcar/message/inputMessage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package racingcar.message;

public class inputMessage {

public static final String START_GAME = "경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)";
public static final String GET_GAME_ROUND = "시도할 회수는 몇회인가요?";

}
6 changes: 6 additions & 0 deletions src/main/java/racingcar/message/outputMessage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package racingcar.message;

public class outputMessage {
public static final String GAME_ROUND = "\n" + "실행 결과";
public static final String GAME_RESULT = "최종 우승자 : ";
}
23 changes: 23 additions & 0 deletions src/main/java/racingcar/model/Car.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package racingcar.model;

public class Car {
private final String name;
private int position = 0;

public Car(String name, int position) {
this.name = name;
this.position = position;
}

public String getName() {
return name;
}

public int getPosition() {
return position;
}

public void setPosition(int position) {
this.position = position;
}
}
27 changes: 27 additions & 0 deletions src/main/java/racingcar/model/racingGame.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package racingcar.model;

import camp.nextstep.edu.missionutils.Randoms;

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

public class racingGame {

public List<Car> saveCars(String[] carNames) {
List<Car> cars = new ArrayList<>();
for (int i = 0; i < carNames.length; i++) {
String name = carNames[i];
cars.add(new Car(name, 0));
}
return cars;
}

public void updatePhase(List<Car> cars) {
for (int j = 0; j < cars.size(); j++) {
int randomNum = Randoms.pickNumberInRange(0, 9);
if (randomNum >= 4) {
cars.get(j).setPosition(cars.get(j).getPosition() + 1);
}
}
}
}
16 changes: 16 additions & 0 deletions src/main/java/racingcar/model/winningResult.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package racingcar.model;

import java.util.List;

public class winningResult {
public int winningScore = 0;

public void winningScore(List<Car> cars) {
for (int m = 0; m < cars.size(); m++) {
if (winningScore < cars.get(m).getPosition()) {
winningScore = cars.get(m).getPosition();
}
}
}

}
63 changes: 63 additions & 0 deletions src/main/java/racingcar/view/inputView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package racingcar.view;

import camp.nextstep.edu.missionutils.Console;
import racingcar.message.exceptionMessage;
import racingcar.message.inputMessage;

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

public class inputView {

public String[] getNames() {
out(inputMessage.START_GAME);
String inputname = Console.readLine();
String[] names = inputname.split(",");
try {
nameRange(names);
sameName(names);
} catch (IllegalArgumentException e) {
getNames();
Copy link

Choose a reason for hiding this comment

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

사용자가 1억번이나 실수하면 프로그램이 터질 것 같습니다!
while 문을 사용해보는건 어떨까요?
아래 예시가 도움이 됬으면 좋겠습니다.

public String[] getNames() {
    repeatInputUntilSuccess(() -> {
        // 여기에 코드 입력
    });
}

private <T> T repeatInputUntilSuccess(Supplier<T> callback) {
    while (true) {
        try {
             return callback.get();
        } catch (IllegalArgumentException e) {
            println("[ERROR] %s", e.getMessage());
        }
    }
}

Copy link
Author

Choose a reason for hiding this comment

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

감사합니다! 재귀 호출을 성능면에서 생각해보지 않은 것 같습니다! 달아주신 코드 참고하겠습니다 :)

}
return names;
}

private void nameRange(String[] names) {
for (String name : names) {
if (name.length() > 5) {
out(exceptionMessage.CAR_NAME_RANGE);
throw new IllegalArgumentException();
}
}
}

private void sameName(String[] names) {
List<String> check = new ArrayList<>();
for (String name : names) {
if (check.contains(name)) {
out(exceptionMessage.SAME_NAME);
throw new IllegalArgumentException();
} else {
check.add(name);
}
}
}

public int getRound() {
out(inputMessage.GET_GAME_ROUND);
String inputround = Console.readLine();
int round = 0;
try {
round = Integer.parseInt(inputround);
} catch (IllegalArgumentException e) {
out(exceptionMessage.ROUND_STIRNG);
getRound();
}
return round;
}

private void out(String text) {
System.out.println(text);
}

}
30 changes: 30 additions & 0 deletions src/main/java/racingcar/view/outputView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package racingcar.view;

import racingcar.message.outputMessage;
import racingcar.model.Car;

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

public class outputView {

public void round(List<Car> cars) {
for (Car car : cars) {
System.out.print(car.getName());
System.out.print(" : ");
System.out.println("-".repeat(car.getPosition()));
}
System.out.println();
}

public void result(List<Car> cars, int firstPrize) {
System.out.print(outputMessage.GAME_RESULT);
List<String> winner = new ArrayList<>();
for (int n = 0; n < cars.size(); n++) {
if (cars.get(n).getPosition() == firstPrize) {
winner.add(cars.get(n).getName());
}
}
System.out.println(String.join(", ", winner));
}
}