Skip to content

유승근 - 자동차 경주 게임 #3

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

Open
wants to merge 16 commits into
base: yuseunggeun
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 FeatureList.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# 기능 리스트

### (구현)1.이름을 입력 받아 해당 이름의 Car 객체들을 생성한다.
- console API를 활용한다.
- 잘못된 값을 입력 시 에러메시지를 출력시키고 다시 입력받는다.
- Car 객체들을 리스트로 관리한다.

### (구현)2.시도할 회수를 입력받고 게임을 시작한다.
- 잘못된 값을 입력 시 에러메시지를 출력시키고 다시 입력받는다.

### (구현)3.자동차마다 0~9 사이 무작위 값을 생성한다.
- Randoms API를 활용한다.

### (구현)4.생성한 값이 4이상이면 전진한다.
- Car 객체의 position 값을 증가시킨다.

### (구현)5.매 이동마다 자동차들의 이동 상황을 출력한다.

### (구현)6.게임이 끝난 후 우승자를 출력한다.
- 우승자가 여러 명일 경우 쉼표를 사용해 구분한다.
7 changes: 4 additions & 3 deletions src/main/java/racingcar/Application.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package racingcar;

public class Application {
public static void main(String[] args) {
// TODO 구현 진행
}
public static void main(String[] args) {
Game game = new Game();
game.initiateGame();
}
}
42 changes: 36 additions & 6 deletions src/main/java/racingcar/Car.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,42 @@
package racingcar;

import camp.nextstep.edu.missionutils.Randoms;
import tools.Utility;

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

public Car(String name) {

this.name = name;
}

public String getName() {

return this.name;
}

public int getPosition() {

return position;
}

public String getPositionString() {

return Utility.repeatString(position, "-");
}
Comment on lines +25 to +28
Copy link

Choose a reason for hiding this comment

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

Utility.repeatString을 사용해서 출력하는 방법 좋은 것 같습니다!

Copy link
Author

Choose a reason for hiding this comment

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

감사합니다 :)


public void updatePosition() {

if (canAdvance()) {
position++;
}
}

private boolean canAdvance() {

public Car(String name) {
this.name = name;
}
return Randoms.pickNumberInRange(0, 9) >= 4;
}

// 추가 기능 구현
}
68 changes: 68 additions & 0 deletions src/main/java/racingcar/Game.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package racingcar;

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

import tools.InputTool;
import tools.PrintTool;

public class Game {
private int currentMove = 0;
private int maxMove;
private final List<Car> cars;

Game() {
cars = new ArrayList<>();
}

public void initiateGame() {

setCars(InputTool.getCarNames());
setMaxMove(InputTool.getMaxMoves());
playGame();
}

private void setCars(String[] carNames) {

for (String carName : carNames) {
cars.add(new Car(carName));
}
}

private void setMaxMove(int maxMove) {

this.maxMove = maxMove;
}

private void playGame() {
System.out.println("실행 결과");
while (currentMove < maxMove) {
PrintTool.printProgress(cars);
currentMove++;
}
PrintTool.printWinners(findWinner());
}

private List<String> findWinner() {

List<String> winners = new ArrayList<>();
int maxPosition = findMaxPosition();

for (Car car : cars) {
if (car.getPosition() == maxPosition) {
winners.add(car.getName());
}
}
return winners;
}

private int findMaxPosition() {

int maxPosition = 0;
for (Car car : cars) {
maxPosition = Math.max(maxPosition, car.getPosition());
Copy link

Choose a reason for hiding this comment

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

if문으로 maxPosition 값을 갱신하는 것이 아닌, Math.max를 사용해 maxPosition을 갱신하는 방법 좋은 것 같습니다!

Copy link
Author

Choose a reason for hiding this comment

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

들여쓰기 규칙을 신경쓰다보니 더 간략하게 표현할 수 있는 방법으로 구현한 것 같습니다. 감사합니다 :)

}
return maxPosition;
}

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

import camp.nextstep.edu.missionutils.Console;

public class InputTool {
public static String[] getCarNames() {

System.out.println("경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)");
String userInput = Console.readLine();
String[] cars = userInput.split(",");
try {
ValidationTool.checkValidNames(cars);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
return getCarNames();
}
return cars;
}

public static int getMaxMoves() {

System.out.println("시도할 회수는 몇회인가요?");
String userInput = Console.readLine();
try {
ValidationTool.checkValidMoves(userInput);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
return getMaxMoves();
}
return Integer.parseInt(userInput);
}
}
27 changes: 27 additions & 0 deletions src/main/java/tools/PrintTool.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package tools;

import java.util.List;

import racingcar.Car;

public class PrintTool {

public static void printProgress(List<Car> cars) {
for (Car car : cars) {
car.updatePosition();
printCarPosition(car);
}
System.out.println();
}

public static void printCarPosition(Car car) {

System.out.println(car.getName() + " : " + car.getPositionString());
}

public static void printWinners(List<String> winners) {

String str = String.join(", ", winners);
System.out.println("최종 우승자 : " + str);
}
}
11 changes: 11 additions & 0 deletions src/main/java/tools/Utility.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package tools;

public class Utility {
public static String repeatString(int count, String str) {
StringBuilder stringBuilder = new StringBuilder();
for (int cnt = 0; cnt < count; cnt++) {
stringBuilder.append(str);
}
return stringBuilder.toString();
}
}
26 changes: 26 additions & 0 deletions src/main/java/tools/ValidationTool.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package tools;

public class ValidationTool {

public static void checkValidNames(String[] cars) {

for (String car : cars) {
if (car.length() > 5) {
throw new IllegalArgumentException("[ERROR] 이름은 5자 이하여야 합니다.");
}
}
}

public static void checkValidMoves(String userInput) {

int inputMoves;
try {
inputMoves = Integer.parseInt(userInput);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("[ERROR] 시도 횟수는 숫자여야 한다.");
}
if (inputMoves <= 0) {
throw new IllegalArgumentException("[ERROR] 시도 횟수는 양의 정수여야 한다.");
}
}
}